反序列化泛型类型与GSON [英] Deserializing Generic Types with GSON

查看:164
本文介绍了反序列化泛型类型与GSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的Andr​​oid应用程序(与GSON库)的一些问题与实施的Json反序列化

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

我做了类

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

和反序列化调用是:

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

问题是,调用后result.posts单持有,而不是MyJson对象LinkedTreeMap对象的一个​​数组(用正确的值那么问题就是反序列化)。当我使用,而不是T.一切MyObject来运行良好,并为MyObject是正确的。

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?

推荐答案

您是否尝试过?

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

修改

看完<一href="http://stackoverflow.com/questions/5554217/google-gson-deserialize-listclass-object-generic-type">this张贴看来你使用键入是正确的。我相信你的问题是使用 T 的。你必须记住,与Java有类型擦除。这意味着,在运行时 T 的所有实例都替换为对象。因此,在运行时要传递GSON什么是真正的 MyJson&LT;对象&gt; 。如果你代替试图与一个具体的类&LT; T&GT; 我认为这是可行的。

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.

<一个href="http://stackoverflow.com/questions/5554217/google-gson-deserialize-listclass-object-generic-type">Google GSON - 反序列化列表&LT;类&GT;目的? (通用型)

这篇关于反序列化泛型类型与GSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆