Gson,带有泛型的ClassCastException
我有以下代码可以反序列化json数组,并且可以正常工作. 但是,如果我尝试迭代该列表,则会收到ClassCastException. 如果我用MyObj替换通用类型T,则迭代有效. 但是我想使反序列化代码通用. 您能帮我解决这个错误吗? 预先感谢.
I have below code to deserialize the json array and it worked find. However, if I try to iterate the list, I am getting ClassCastException. If I replace generic type T with MyObj and the iteration works. But I wanted to make the deserialization code to be generic. Could you please help me how I can fix this error? Thanks in advance.
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to MyObj
json反序列化代码
json deserialization code
public static <T> List<T> mapFromJsonArray(String respInArray) {
Type listType = new TypeToken<ArrayList<T>>(){}.getType();
List<T> ret = new Gson().fromJson(respInArray, listType);
return ret;
}
for循环出错.
List<MyObj> myObjResponse = JsonUtil.<MyObj>mapFromJsonArray(jsonResponse);
for(MyObj obj : myObjResponse){ // Class cast exception
//do something
}
您肯定需要为mapFromJsonArray
提供比这更多的信息-这是不可避免的,因为对于每次调用<T>
的绑定都是在运行时完全删除. TypeToken
所做的所有事情都是试图验证您没有的信息.
You certainly need to give mapFromJsonArray
more information than this--that is unavoidable, since the binding of <T>
for each invocation is entirely erased at runtime. All your TypeToken
is doing is trying to reify information that you don't have.
但是您所需要做的就是传递元素类型,这将起作用:
But all you need to do is pass in the element type, and this will work:
public static <T> List<T> mapFromJsonArray(String respInArray, Class<T> elementClass) {
Type listType = new TypeToken<List<T>>(){}
.where(new TypeParameter<T>(){}, elementClass).getType();
return new Gson().fromJson(respInArray, listType);
}
打电话并不比您以前笨拙:
It's not any more clunky to call than what you had:
List<MyObj> myObjResponse = mapFromJsonArray(jsonResponse, MyObj.class);