use*_*799 5 java generics serialization gson
我有下面的代码反序列化json数组,它找到了工作.但是,如果我尝试迭代列表,我将得到ClassCastException.如果我用MyObj替换泛型类型T并且迭代起作用.但我想让反序列化代码变得通用.你能帮我解决一下这个错误吗?提前致谢.
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to MyObj
Run Code Online (Sandbox Code Playgroud)
json反序列化代码
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;
}
Run Code Online (Sandbox Code Playgroud)
for循环中的错误.
List<MyObj> myObjResponse = JsonUtil.<MyObj>mapFromJsonArray(jsonResponse);
for(MyObj obj : myObjResponse){ // Class cast exception
//do something
}
Run Code Online (Sandbox Code Playgroud)
您当然需要提供mapFromJsonArray比这更多的信息——这是不可避免的,因为<T>每个调用的绑定在运行时都被完全删除。你所做的一切TypeToken就是试图具体化你没有的信息。
但您需要做的就是传入元素类型,这样就可以工作:
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);
}
Run Code Online (Sandbox Code Playgroud)
调用并不比您所拥有的更笨重:
List<MyObj> myObjResponse = mapFromJsonArray(jsonResponse, MyObj.class);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2603 次 |
| 最近记录: |