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?
Since you have on your hands a
JSONArray, which is comprised ofJSONObjects, you can iterate over this array accessing eachJSONObjectand retrieving its properties.For convenience, we can define a POJO that would correspond to
JSONObject. It can be represented either as aclassor a Java 16record, I'll go with a record because of its conciseness:That's how we can parse a
JSONArrayinto aListof POJO:Output:
Alternatively, this logic can be implemented using Stream API. To generate a stream from a
JSONArraywe can make use of the functionality offered byStreamSupportutility class.