简体   繁体   中英

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. The JSON response is in the below format.

{
  "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. I'm using Jackson to parse the data.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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