Parsing JSON Arrays into Java Arrays
The provided code successfully parses JSON objects and extracts their key-value pairs. However, it faces challenges when dealing with complex JSON structures like arrays within objects.
To access and convert array values into a Java array, we can utilize the getJSONArray method:
JSONObject myjson = new JSONObject(the_json); JSONArray the_json_array = myjson.getJSONArray("profiles");
This returns an array object named the_json_array.
To iterate over the array:
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); arrays.add(another_json_object); }
Finally, to convert the ArrayList into a Java array:
JSONObject[] jsons = new JSONObject[arrays.size()]; arrays.toArray(jsons);
This approach allows us to extract and manipulate JSON arrays into Java array structures for further processing.
The above is the detailed content of How to Parse JSON Arrays into Java Arrays?. For more information, please follow other related articles on the PHP Chinese website!