在反序列化时,必须指定T
的类型.如果Gson
不知道要实例化哪一个Type
,那么如何创建posts
中的List
?它不可能永远保持T
.因此,您可以提供类型T
作为Class
参数.
Now assuming, the type of posts
was String
you would deserialize MyJson<String>
as (I've also added a String json
parameter for simplicity; you would read from your reader
as before):
doInBackground(String.class, "{posts: [\"article 1\", \"article 2\"]}");
protected MyJson<T> doInBackground(Class<T> type, String json, Void... params) {
GsonBuilder gson = new GsonBuilder();
Type collectionType = new TypeToken<MyJson<T>>(){}.getType();
MyJson<T> myJson = gson.create().fromJson(json, collectionType);
System.out.println(myJson.getPosts()); // ["article 1", "article 2"]
return myJson;
}
类似地,反序列化Boolean
个对象中的MyJson
个
doInBackground(Boolean.class, "{posts: [true, false]}");
protected MyJson<T> doInBackground(Class<T> type, String json, Void... params) {
GsonBuilder gson = new GsonBuilder();
Type collectionType = new TypeToken<MyJson<T>>(){}.getType();
MyJson<T> myJson = gson.create().fromJson(json, collectionType);
System.out.println(myJson.getPosts()); // [true, false]
return myJson;
}
I've assumed MyJson<T>
for my examples to be as
public class MyJson<T> {
public List<T> posts;
public List<T> getPosts() {
return posts;
}
}
所以,如果你想反序列化一个List<MyObject>
,你可以调用这个方法
// assuming no Void parameters were required
MyJson<MyObject> myJson = doInBackground(MyObject.class);