user3872094
user3872094

Reputation: 3351

how to get json from inside a json

I've the below json data.

{
  "RestResponse" : {
    "messages" : [ "More webservices are available at http://www.groupkt.com/post/f2129b88/services.htm", "Total [249] records found." ],
    "result" : [ {
      "name" : "Afghanistan",
      "alpha2_code" : "AF",
      "alpha3_code" : "AFG"
    }, {
      "name" : "Åland Islands",
      "alpha2_code" : "AX",
      "alpha3_code" : "ALA"
    }, {
      "name" : "Albania",
      "alpha2_code" : "AL",
      "alpha3_code" : "ALB"
    }, {
      "name" : "Algeria",
      "alpha2_code" : "DZ",
      "alpha3_code" : "DZA"
    }]
  }
}

Here I need to loop through the country names and print it in my console.

I'm trying the below code.

ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> map = mapper.readValue(text, new TypeReference<Map<String, Object>>() {
            });

            Map<String, Object> map1 = (Map<String, Object>) map.get("RestResponse");
            Map<String, Object> map2 = (Map<String, Object>) map1.get("result");



            System.out.println(map1);

When I run this I get exception as

Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Map
    at onlyJava.Countries.getTheCurrentWeather(Countries.java:45)
    at onlyJava.Test.main(Test.java:6)

when I comment out Map<String, Object> map2 = (Map<String, Object>) map1.get("result");, it gives me the result starting from messages:.... till the end.

please let me know where am I going wrong and how can I fix this.

Updated code.

ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> map = mapper.readValue(text, new TypeReference<Map<String, Object>>() {
            });

            Map<String, Object> map1 = (Map<String, Object>) map.get("RestResponse");
            List<Object> resultList = new ArrayList<Object>();
            resultList = mapper.readValue(map1.get("result"), new TypeReference<List<Object>>() {
            });

            System.out.println(resultList);

Thanks

Upvotes: 0

Views: 258

Answers (3)

Manan Sheth
Manan Sheth

Reputation: 150

Result is of type list, so in order to parse it properly you need to do something like below:

List<Object> resultList = new ArrayList<Object>();
resultList = JsonMapper.readValue(map1.get("result"), new TypeReference<List<Object>>(){});

Also, to simplify rather than parsing node one by one, you can create a POJO of result object and have json mapper do automatic conversion.

EDIT: In order to have proper mapping create a pojo of root and subsequent objects and parse it as per below:

ObjectMapper mapper = new ObjectMapper();
    mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
    String jsonString = "{\"RestResponse\":{\"messages\":[\"More webservices are available at http://www.groupkt.com/post/f2129b88/services.htm\", \"Total [249] records found.\" ],\"result\":[{\"name\":\"Afghanistan\",\"alpha2_code\":\"AF\",\"alpha3_code\":\"AFG\"}, {\"name\":\"Åland Islands\",\"alpha2_code\":\"AX\",\"alpha3_code\":\"ALA\"}, {\"name\":\"Albania\",\"alpha2_code\":\"AL\",\"alpha3_code\":\"ALB\"}, {\"name\":\"Algeria\",\"alpha2_code\":\"DZ\",\"alpha3_code\":\"DZA\"}]}}";
    Root response = null;
    try {

        response = mapper.readValue(jsonString, Root.class);

        for (Result result : response.getRestResponse().getResult())
            System.out.println("Country Name: " + result.getName());
    } catch (IOException e) {
        e.printStackTrace();
    }

Root Class:

RestResponseNode RestResponse;

public RestResponseNode getRestResponse() {
    return RestResponse;
}

public void setRestResponse(RestResponseNode restResponse) {
    RestResponse = restResponse;
}

@Override
public String toString() {
    return "Root [RestResponseNode=" + RestResponse + "]";
}

RestResponseNode Class:

List<String> messages;
List<Result> result;

public List<String> getMessages() {
    return messages;
}

public void setMessages(List<String> messages) {
    this.messages = messages;
}

public List<Result> getResult() {
    return result;
}

public void setResult(List<Result> result) {
    this.result = result;
}

@Override
public String toString() {
    return "RestResponseNode [messages=" + messages + ", result=" + result + "]";
}

Result Class:

String name;
String alpha2_code;
String alpha3_code;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAlpha2_code() {
    return alpha2_code;
}

public void setAlpha2_code(String alpha2_code) {
    this.alpha2_code = alpha2_code;
}

public String getAlpha3_code() {
    return alpha3_code;
}

public void setAlpha3_code(String alpha3_code) {
    this.alpha3_code = alpha3_code;
}

@Override
public String toString() {
    return "Result [name=" + name + ", alpha2_code=" + alpha2_code + ", alpha3_code=" + alpha3_code + "]";
}

Upvotes: 1

Divyesh Kanzariya
Divyesh Kanzariya

Reputation: 3789

You are getting jsonObject. Value against key "RestResponse" inside "Result" is jsonArray below code for find country name from json.

test with Json Library : org.json

String jsonString = "{ \"RestResponse\" : { \"messages\" : [ \"More webservices are available at http://www.groupkt.com/post/f2129b88/services.htm\", \"Total [249] records found.\" ], \"result\" : [ { \"name\" : \"Afghanistan\", \"alpha2_code\" : \"AF\", \"alpha3_code\" : \"AFG\" }, { \"name\" : \"Åland Islands\", \"alpha2_code\" : \"AX\", \"alpha3_code\" : \"ALA\" }, { \"name\" : \"Albania\", \"alpha2_code\" : \"AL\", \"alpha3_code\" : \"ALB\" }, { \"name\" : \"Algeria\", \"alpha2_code\" : \"DZ\", \"alpha3_code\" : \"DZA\" }] } }";
JSONObject jObject = new JSONObject(jsonString);
JSONObject obj1 = jObject.getJSONObject("RestResponse");
JSONArray result = obj1.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
    JSONObject company = result.getJSONObject(i);
    String name = company.getString("name");
    System.out.println("Country Name : "+name);
}

Output :

Country Name : Afghanistan
Country Name : Åland Islands
Country Name : Albania
Country Name : Algeria

Upvotes: 1

Ashish
Ashish

Reputation: 36

You are getting jsonObject. Value against key "RestResponse" is inside {} brackets that its again a json Object thats why you are able to map it to a Map. but the value against key "result" is inside [] brackets and that is a list not a json object so you can not assign it to a Map. You should create an Arraylist an assign it to that.

Upvotes: 1

Related Questions