After looking at * questions I could not find any solution that fix this problem.
在查看*问题后,我找不到解决此问题的任何解决方案。
I am trying to use GSON and have implemented a generic method like this:
我正在尝试使用GSON并实现了这样的通用方法:
public <T> List<T> deserializeList(String json) {
Gson gson = new Gson();
Type type = (new TypeToken<List<T>>() {}).getType();
return gson.fromJson(json, type);
}
Call to this method is done through this :
通过以下方式调用此方法:
parser.<Quote>deserializeList(result)
However the result that I am getting is this:
但是我得到的结果是这样的:
And when I am trying to access an object, I get this error:
当我试图访问一个对象时,我收到此错误:
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to model.Quote
The JSON string is:
JSON字符串是:
[
{
"id": 269861,
"quote": "People living deeply have no fear of death.",
"author": "Anais Nin",
"genre": "life",
"tag": null,
"createdAt": "2016-04-16T13:13:36.928Z",
"updatedAt": "2016-04-16T13:13:36.928Z"
}
]
2 个解决方案
#1
1
I would think you could write the method like so to explicitly provide the Type
我认为你可以像这样编写方法来显式提供Type
public <T> List<T> deserializeList(String json, Type type) {
Gson gson = new Gson();
return gson.fromJson(json, type);
}
Though, passing around (new TypeToken<List<Model>>() {}).getType();
looks a little messy.
但是,传递(new TypeToken
>(){})。getType();看起来有点乱。
I'm not too familiar with type erasure, but I bet that's related to the problem.
我不太熟悉类型擦除,但我敢打赌这与问题有关。
#2
0
The above parsing method is wrong and the following code is modified:
上面的解析方法是错误的,并修改了以下代码:
public static <T> List<T> getObjectList(String jsonString,Class<T> cls){
List<T> list = new ArrayList<T>();
try {
Gson gson = new Gson();
JsonArray arry = new JsonParser().parse(jsonString).getAsJsonArray();
for (JsonElement jsonElement : arry) {
list.add(gson.fromJson(jsonElement, cls));
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
#1
1
I would think you could write the method like so to explicitly provide the Type
我认为你可以像这样编写方法来显式提供Type
public <T> List<T> deserializeList(String json, Type type) {
Gson gson = new Gson();
return gson.fromJson(json, type);
}
Though, passing around (new TypeToken<List<Model>>() {}).getType();
looks a little messy.
但是,传递(new TypeToken
>(){})。getType();看起来有点乱。
I'm not too familiar with type erasure, but I bet that's related to the problem.
我不太熟悉类型擦除,但我敢打赌这与问题有关。
#2
0
The above parsing method is wrong and the following code is modified:
上面的解析方法是错误的,并修改了以下代码:
public static <T> List<T> getObjectList(String jsonString,Class<T> cls){
List<T> list = new ArrayList<T>();
try {
Gson gson = new Gson();
JsonArray arry = new JsonParser().parse(jsonString).getAsJsonArray();
for (JsonElement jsonElement : arry) {
list.add(gson.fromJson(jsonElement, cls));
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}