com.google.gson.internal.LinkedTreeMap cannot be cast to List1.class

来源:互联网 发布:淘宝账号无法登陆 编辑:程序博客网 时间:2024/05/22 14:52

在使用Gson解析json时,我定义了三个entity:1、Root.class;
public Root(String reason, Result result, int error_code) {
super();
this.reason = reason;
this.result = result;
this.error_code = error_code;
}
2、Result.class;
public Result(String key, List list) {
super();
this.key = key;
this.list = list;
}
3、List1.class;
public List1(String c1, String c2, String c3, String c4t1, String c4t1url, String c4r, String c4t2, String c4t2url,
String c51, String c52, String c52Link, String c53, String c53Link, String c54, String c54Link) {
super();
this.c1 = c1;
this.c2 = c2;
this.c3 = c3;
c4T1 = c4t1;
c4T1URL = c4t1url;
c4R = c4r;
c4T2 = c4t2;
c4T2URL = c4t2url;
this.c51 = c51;
this.c52 = c52;
this.c52Link = c52Link;
this.c53 = c53;
this.c53Link = c53Link;
this.c54 = c54;
this.c54Link = c54Link;
}
在使用过程中,遇到的问题是当我得到Result实例后,通过List list=result.getList()得到List数组,再通过list.get(0);取到第一个object,即List1 list1;List1 list1=list.get(0);但是,这里老是报错:com.google.gson.internal.LinkedTreeMap cannot be cast to List1 class
网上说是due to type erasure, the parser can’t fetch the real type T at runtime。就是解析器无法取到真实的List1.class。
那么怎么办呢?
首先,将List list,转换为String类型
public static String arrayToString(List list) {
Gson g = new Gson();
return g.toJson(list);
}
然后,再把String转换为我们要的object(解析器就可以取到我们想要的object类了),这里也回答了为什么要将List转为String类型public static <T> List<T> stringToArray(String s, Class<T[]>clazz) {
T[] arr = new Gson().fromJson(s, clazz);
return Arrays.asList(arr); //or return Arrays.asList(new Gson().fromJson(s, clazz)); for a one-liner
}

MainActivity.class的主要代码:
String url=”http://op.juhe.cn/onebox/football/team?key=573fb9262c954b572b9cbd4a62505db4&team=%E6%9B%BC%E8%81%94”;
// mQueue.add(gsonRequest);
GsonRequestgsonRequest1=new GsonRequest(url, Root.class, new Response.Listener() {
@Override
public void onResponse(Root root) {
// TODO Auto-generated method stub
Result result=root.getResult();
List list=result.getList();
String str=arrayToString(list);
Log.i(“TAG”, str);
String c1=stringToArray(str, List1[].class).get(0).getC1();
Log.i(“TAG”, list.get(0)+”“);
Log.i(“TAG”, list.toString());
Log.i(“TAG”, c1);
}
}, new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.e(“TAG”, error.getMessage(),error);
}
});
mQueue.add(gsonRequest1);

0 0