JSON Parsing: Converting JSON Values into Java Arrays
The sample code provided can effectively extract the keys and values from a JSON object. However, if the JSON contains an array as a value, we need to transform that array into a Java array for further processing.
Considering the JSON:
{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}
To capture the array, use these steps:
JSONObject myjson = new JSONObject(the_json); JSONArray the_json_array = myjson.getJSONArray("profiles");
the_json_array now holds the array object.
To iterate through the array:
int size = the_json_array.length(); ArrayList<JSONObject> arrays = new ArrayList<JSONObject>(); for (int i = 0; i < size; i++) { JSONObject another_json_object = the_json_array.getJSONObject(i); //Blah blah blah... arrays.add(another_json_object); } //Finally JSONObject[] jsons = new JSONObject[arrays.size()]; arrays.toArray(jsons); //The end...
Determine if the data is an array by checking if the first character is '['.
This approach allows you to capture and convert arrays stored as JSON values into Java arrays, enabling further manipulation and analysis of the data.
The above is the detailed content of How to Convert JSON Arrays into Java Arrays?. For more information, please follow other related articles on the PHP Chinese website!