Home > Java > javaTutorial > How to extract an array of JSON objects from a nested JSON in Java?

How to extract an array of JSON objects from a nested JSON in Java?

Susan Sarandon
Release: 2024-11-09 04:01:02
Original
199 people have browsed it

How to extract an array of JSON objects from a nested JSON in Java?

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:

  1. Create a JSONObject from the JSON string.
  2. Use the getJSONArray method of JSONObject to retrieve the array.
  3. Iterate over the array using length method and store its elements in a List of JSONObject instances.
  4. Convert the List into an array of JSONObject using toArray method.

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);
Copy after login

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!

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