Home > Java > javaTutorial > How to Convert JSON Arrays into Java Arrays?

How to Convert JSON Arrays into Java Arrays?

Barbara Streisand
Release: 2024-11-09 13:42:02
Original
1055 people have browsed it

How to Convert JSON Arrays into Java Arrays?

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}]}
Copy after login

To capture the array, use these steps:

JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");
Copy after login

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...
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template