1

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?

2
  • Possible duplicate of How to parse JSON in Java Commented Apr 1, 2018 at 15:24
  • What you get is a Response, which contains a List<Country>. But you try to parse this Response as a List<Country>. So that can' work. Parse the response as a Response, and it will work fine. Then get the list of countries out of the parsed Response. Commented Apr 1, 2018 at 15:25

1 Answer 1

2

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;
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.