【问题标题】:How to parse a nested JSON response to a list of Java objects如何解析对 Java 对象列表的嵌套 JSON 响应
【发布时间】:2018-04-01 15:20:51
【问题描述】:

我希望将带有嵌套 JSON 数据的响应解析为 Java 对象列表。 JSON 响应采用以下格式。

{
  "IsSuccess": true,
  "TotalCount": 250,
  "Response": [
    {
      "Name": "Afghanistan",
      "CurrencyCode": "AFN",
      "CurrencyName": "Afghan afghani"
    },
    {
      "Name": "Afghanistan",
      "CurrencyCode": "AFN",
      "CurrencyName": "Afghan afghani"
    },
    {
      "Name": "Afghanistan",
      "CurrencyCode": "AFN",
      "CurrencyName": "Afghan afghani"
    }
   ]
}

我创建了相应的 Country 类,用于解析为 POJO。我正在使用 Jackson 来解析数据。

Client c = ClientBuilder.newClient();
        WebTarget t = c.target("http://countryapi.gear.host/v1/Country/getCountries");
        Response r = t.request().get();
        String s = r.readEntity(String.class);
        System.out.println(s);
        ObjectMapper mapper = new ObjectMapper();
        try {
            List<Country> myObjects = mapper.readValue(s, new TypeReference<List<Country>>(){});
            System.out.println(myObjects.size());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

国家/地区的实际列表带有 JSON 字符串中的“响应”。如何检索 Response 下的内容,然后将其解析为国家列表?

【问题讨论】:

  • How to parse JSON in Java的可能重复
  • 你得到的是一个响应,其中包含一个列表。但是您尝试将此响应解析为 List。所以那行不通。将响应解析为响应,它将正常工作。然后从解析后的响应中获取国家列表。

标签: java json jackson gson pojo


【解决方案1】:

不确定您使用的客户端 API 不能简单地提供所需类型的实体。大多数客户端应该有实用方法来进行这种转换。无论如何,这里有一种方法可以实现你想要的:

final JsonNode jsonNode = mapper.readTree(jsonString);
final ArrayNode responseArray = (ArrayNode) jsonNode.get("Response");
//UPDATED to use convertValue()
final List<Country> countries = mapper.convertValue(responseArray, new TypeReference<List<Country>>(){});

国家.class

 class Country {
    @JsonProperty("Name")
    public String name;
    @JsonProperty("CurrencyCode")
    public String currencyCode;
    @JsonProperty("CurrencyName")
    public String currencyName;
 }

【讨论】:

    猜你喜欢
    • 2019-03-06
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    相关资源
    最近更新 更多