简体   繁体   English

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

[英]How to parse a nested JSON response to a list of Java objects

I am looking to parse a response with nested JSON data into a list of Java objects. 我希望将带有嵌套JSON数据的响应解析为Java对象列表。 The JSON response is in the below format. 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"
    }
   ]
}

I have the corresponding Country class created for parsing as POJO. 我有相应的Country类,可以将其解析为POJO。 I'm using Jackson to parse the data. 我正在使用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();
        }

The actual list of countries is withing the "Response" in the JSON String. 实际的国家/地区列表与JSON字符串中的“响应”一起显示。 How would I retrieve the contents under Response and then parse it as a list of countries? 我将如何检索“响应”下的内容,然后将其解析为国家列表?

Not sure what Client API you are using that cannot simply provide entity of desired type. 不确定所使用的客户端API不能简单地提供所需类型的实体。 Most clients should have utility methods to do such conversion. 大多数客户端应具有实用程序方法来进行这种转换。 Anyways, here's a way you can achieve what you want: 无论如何,这是一种实现所需目标的方法:

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 Country.class

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM