我在Android应用程序(使用Gson库)中实现Json反序列化时遇到了一些问题

我已经像这样上课了

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

问题在于这个结果.调用后的posts列表包含一个LinkedTreeMap对象数组(具有正确的值,所以问题是反序列化),而不是MyJson对象.当我使用MyObject而不是T时,一切都运行良好,MyObject是正确的.

那么,有没有办法在不创建自定义反序列化程序的情况下实现反序列化调用呢?

推荐答案

在反序列化时,必须指定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);

Json相关问答推荐

时间和日期数据绘制不正确

Jolt Transformation—如果子对象为空,则将父对象更新为空

Vega-Lite时钟(使用Vega-Lite中的计时器)

褐煤面积图中的分选问题

解析Ansible AWS ec2_security_group中的json以提取安全组ID

如何获取 JSON 对象字段值和同一 JSON 对象的下一个数组中的字段值?

删除 JOLT 中的方括号

具有 (RegEx) 模式的 json-schema 中的枚举

将=分隔值文件转换为:json文件

如何从字符串中创建一个逗号分隔的列表,由 API 中的 JSON 对象内的编号空格分隔?

嵌套 JSON 到 CSV(多级)

将 json 文件转换为 json 对象会打乱对象的顺序

如何从条带订阅响应对象中正确获取 struct 项?

如何将 XML 转换为 PsCustomObject 以允许最终导出为 JSON?

苗条的 JSON 输出

编写 JSON 日志(log)文件的格式?

使用 JSON 的 javascript 深拷贝

jQuery fullcalendar 发送自定义参数并使用 JSON 刷新日历

ASP.NET MVC 读取原始 JSON 发布数据

在 JSON.NET 中序列化派生类时的字段顺序