Home  >  Article  >  Java  >  How to Convert JSON Values to an Array in Java?

How to Convert JSON Values to an Array in Java?

DDD
DDDOriginal
2024-11-11 01:42:02717browse

How to Convert JSON Values to an Array in Java?

Converting JSON Values to Array in Java

When working with JSON, it's often necessary to convert specific values into arrays that can be manipulated programmatically. One such scenario arises when encountering JSON structures with values stored as arrays.

Consider the following JSON:

{
  "profiles": [
    { "name": "john", "age": 44 },
    { "name": "Alex", "age": 11 }
  ]
}

To access the array of profiles, the following code snippet can be used:

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

This step returns a JSONArray object that represents the array of profiles.

Iterating through the profiles 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);
    // Manipulate each profile object as needed...
    arrays.add(another_json_object);
}

This loop iterates through the array and retrieves each profile object as a JSONObject. These objects can be further processed or stored for future manipulation.

Finally, to convert the ArrayList of JSONObjects into an array of JSONObjects, the following code can be used:

JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);

This step allows us to work with the array using standard Java array manipulation techniques.

It's important to check if the data being parsed is indeed an array by verifying that the first character of the data is "[".

The above is the detailed content of How to Convert JSON Values to an Array in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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