【问题标题】:Parsing JSON using GSON to get "content"使用 GSON 解析 JSON 以获取“内容”
【发布时间】:2018-12-04 11:58:42
【问题描述】:

我一直在尝试使用 GSON 从 JSON 获取所有预订的列表,但不断收到错误消息。难道我做错了什么?如果是,那么我应该如何解决这个问题?

我的尝试:

Gson gson = new Gson();
Wrapper reservations = gson.fromJson(response.toString(), Wrapper.class);

类:

class Wrapper{
    Long id;
    Long personId;
    List<Long> SeatsIDs;
}

PS GSON 中是否有解决方案来摆脱所有“链接”?

 {
  "links": [
    {
      // a lot of stuff
    }
  ],
  "content": [
    {
      "id": 1,
      "personID": 12335,
      "seatsIDs": [
        5,
        7,
        4
      ],
      "links": [
        {
           // a lot of stuff
        },
        {
           // a lot of stuff
        }
      ]
    },
    {
      "id": 2,
      "personID": 77777,
      "seatsIDs": [
        1,
        2,
        3
      ],
      "links": [
        {
           // a lot of stuff
        },
        {
           // a lot of stuff
        }
      ]
    }
  ]
}

【问题讨论】:

  • 你能解释一下你有什么错误吗?

标签: java json gson


【解决方案1】:

我们没有关于您的错误的描述。但据我所知,您想反序列化 content 数组中的每个条目。但是,您要求 GSON 反序列化完整响应。

一种可能的解决方案是创建一个类似于您的 Json 的类结构:

// Getters and setters omitted
class Response {
  List<Link> links;
  List<Wrapper> content; 
}
// ...
Response response = gson.fromJson(response.toString(), Response.class);
Wrapper first = response.getContent().get(0);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-03
    • 2011-02-12
    • 2012-01-02
    • 1970-01-01
    • 2015-10-14
    • 2016-02-17
    相关资源
    最近更新 更多