Gson,带有泛型的ClassCastException [英] Gson, ClassCastException with Generics

查看:94
本文介绍了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);

这篇关于Gson,带有泛型的ClassCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆