Search code examples
javajsonjacksongsonpojo

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?


Solution

  • 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;
     }