How to get childs of this JSON Object in Java

57 views Asked by At

I am using volley to post data to the server and this is the response I get from the server.

{"result":[{"result":"success","id":"345"}]}

How can I get value of id from this response.

I tried like this, but I get whole JSONArray in response.

JSONArray obj = new JSONObject(response).getJSONArray("result"); 
JSONArray resp = obj.optJSONArray(0);

How to get value of id & result?

1

There are 1 answers

0
Alexander Ivanchenko On

How to get value of id & result?

Since you have on your hands a JSONArray, which is comprised of JSONObjects, you can iterate over this array accessing each JSONObject and retrieving its properties.

For convenience, we can define a POJO that would correspond to JSONObject. It can be represented either as a class or a Java 16 record, I'll go with a record because of its conciseness:

public record Result(String result, int id) {}

That's how we can parse a JSONArray into a List of POJO:

String response = """
    {"result":[{"result":"success","id":"345"}]}
""";
    
JSONArray array = new JSONObject(response).getJSONArray("result");
        
List<Result> results = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
    JSONObject res = (JSONObject) array.get(i);
    results.add(new Result(res.getString("result"), res.getInt("id")));
}
        
results.forEach(System.out::println);

Output:

Result[result=success, id=345]

Alternatively, this logic can be implemented using Stream API. To generate a stream from a JSONArray we can make use of the functionality offered by StreamSupport utility class.

JSONArray array = new JSONObject(response).getJSONArray("result");
        
List<Result> results = StreamSupport.stream(array.spliterator(), false) // Stream<Object>
    .map(JSONObject.class::cast) // Stream<JSONObject>
    .map(jsonObject ->           // Stream<Result>
        new Result(jsonObject.getString("result"), jsonObject.getInt("id"))
    )
    .toList(); // for Java 16+ or collect(Collectors.toList())