Use Gson parse Json array of generic type erase problems encountered Solution

Google Gson Json conversion method has the following sequence:

Object fromJson public (String JSON, the Type typeOfT);
. 1
can use it to parse an array. As follows, using this method to resolve Json string array type MyBean List of methods are available.

List <MyBean> LST = Gson new new () fromJson (Data, new new TypeToken <List <MyBean >> () {} getType ().);.
. 1
, but if the generic MyBean to T, this packaging method is as follows:

List<T> lst = new Gson().fromJson(data, new TypeToken<List<T>>(){}.getType());
public static <T> List<T> parseJson2List(String data, Class<T> clazz){
try {
return new Gson().fromJson(data, new TypeToken<List<T>>(){}.getType());
} catch(Throwable e){
e.printStackTrace();
return null;
}
}
1
2
3
4
5
6
7
8
9
例,实例化泛型为Test

{the Test class
Private ID String;
Private String name;
Private String value;
}
. 1
2
. 3
. 4
. 5
calls the packaging method is as follows:

List <Test> lst = parseJson2List ( new String ( "[{id: 'myid', name: 'myname', value: 'myvaule'}, {id: 'myid', name: 'myname', value: 'myvaule '}] "), Test.class);
. 1
debugging results below, LinkedTreeMap array object type, the type is not expected Test.
Here Insert Picture Description

The reason: generics at compile-time type erasure cause, type erase visible link below:

http://stackoverflow.com/questions/20773850/gson-typetoken-with-dynamic-arraylist-item-type

http://blog.csdn.net/gstormspire/article/details/7638638

Solution:


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;
}

Guess you like

Origin www.cnblogs.com/hyhy904/p/10935220.html