如何解析对 Java 对象列表的嵌套 JSON 响应

How to parse a nested JSON response to a list of Java objects

我希望将带有嵌套 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"
    }
   ]
}

我创建了相应的国家 class 用于解析为 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" 中。我如何检索 Response 下的内容,然后将其解析为国家列表?

不确定您使用的客户端 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>>(){});

Country.class

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