VizGhar VizGhar - 1 year ago 138
Java Question

Deserializing Generic Types with GSON

I have some problems with implementation of Json Deserialization in my Android application (with Gson library)

I've made class like this

public class MyJson<T>{
public List<T> posts;

And Deserialization call is:

public class JsonDownloader<T> extends AsyncTask<Void, Void, MyJson<T>> {
protected MyJson<T> doInBackground(Void... params) {
Reader reader = new InputStreamReader(content);
GsonBuilder gson = new GsonBuilder();
Type collectionType = new TypeToken<MyJson<T>>() {}.getType();
result = gson.create().fromJson(reader, collectionType);

Problem is that result.posts list after call holds one Array of LinkedTreeMap Objects(with correct values so problem is Deserialization) instead of MyJson Objects. When I use MyObject instead of T everything is running fine and MyObject is correct.

So is there any way to implement deserialization call without creating custom deserializer?

Answer Source

Have you tried?

gson.create().fromJson(reader, MyJson.class);


After reading this post it seems that you use of Type is correct. I believe your issue is the use of T. You must remember that with Java there is type-erasure. This means that at runtime all instances of T are replaced with Object. Therefore at runtime what you are passing GSON is really MyJson<Object>. If you tried this with a concrete class in place of <T> I believe it would work.

Google Gson - deserialize list<class> object? (generic type)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download