Extracting an Array from a Nested JSON
In this question, we're presented with a Java code snippet that parses a JSON string. The JSON represents a key-value pair, where the value is an array of objects. The user wants to know how to access and store the array in a Java format.
To parse a nested JSON and turn its values into an array, follow these steps:
Here's an example:
JSONObject myjson = new JSONObject(the_json); JSONArray the_json_array = myjson.getJSONArray("profiles"); int size = the_json_array.length(); ArrayList<JSONObject> arrays = new ArrayList<>(); for (int i = 0; i < size; i++) { JSONObject another_json_object = the_json_array.getJSONObject(i); // Process the inner JSONObject... arrays.add(another_json_object); } // Convert ArrayList to JSONObject array JSONObject[] jsons = new JSONObject[arrays.size()]; arrays.toArray(jsons);
Note that you'll need to check if the value is an array before using the getJSONArray method. You can do this by checking if the first character of the value string is a square bracket ('[').
The above is the detailed content of How to extract an array of JSON objects from a nested JSON in Java?. For more information, please follow other related articles on the PHP Chinese website!