【问题标题】:Gson array parserGson 数组解析器
【发布时间】:2015-05-21 10:41:03
【问题描述】:

我有这种形式的 json 响应:

String json = "{\"0\":{    \"title\" :\"title 1\" ,   \"time\" : \"15:00\"    } ,\"1\":{    \"title\" : \"title 2\"  ,  \"time\" :\"16:00\"   }}";

这是我的班级,我正在尝试将其映射到:

    public class News implements Seriaizable{
        @SerializedName("title")
        private String title;

        @SerializedName("time")
        private String time;
}

我正在苦苦挣扎,因为我有一个没有名称的数组,其中包含大量其他数组。

 Gson gson = new GsonBuilder().setPrettyPrinting().create();
                    News obj = gson.fromJson(reader, News.class);

谁能指导我正确的方向?

【问题讨论】:

  • Json 响应看起来不太好,title 和 time 的值在哪里?其次,新闻类是什么?
  • 是的,我的错,没有正确填写响应并更正了班级名称。

标签: android arrays json gson


【解决方案1】:

您的 JSON 格式不正确。我添加了一些逗号来更正它。

你可以通过使用地图来解决这个问题:

String json = "{\"0\":{    \"title\" :\"title 1\" ,   \"time\" : \"15:00\"    } ,\"1\":{    \"title\" : \"title 2\"  ,  \"time\" :\"16:00\"   }}";

Gson gson = new Gson();

Type type = new TypeToken<Map<Integer, News>>() {}.getType();

Map<Integer, News> map = gson.fromJson(json, type);

参考:https://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples

【讨论】:

    猜你喜欢
    • 2017-02-01
    • 1970-01-01
    • 2015-06-12
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多