利用Gson把json转化成Java List异常问题

Java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to …..

我需要把一串json转化成Java List 最初是这样写的:

private List<CourseDetailsBean.MsgBean.VideoListBean> mList = new ArrayList<CourseDetailsBean.MsgBean.VideoListBean>();

 Gson gson=new Gson();

 mList= gson.fromJson(str,ArrayList.class);

当调用的时候:

final CourseDetailsBean.MsgBean.VideoListBean bean = mList.get(postion);
就会报以下错误:

java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to ….. 

解决办法:

mList= gson.fromJson(str,new TypeToken<List<CourseDetailsBean.MsgBean.VideoListBean>>(){}.getType());

造成这种问题的原因是 
泛型在编译期类型被擦除导致的

public static <T> List<T> fromJsonArray(String json, Class<T> clazz) throws Exception {
List<T> lst = new ArrayList<T>();

JsonArray array = new JsonParser().parse(json).getAsJsonArray();
for(final JsonElement elem : array){
lst.add(new Gson().fromJson(elem, clazz));
}

return lst;
}



你可能感兴趣的:(java,android,异常)