Home > Java > javaTutorial > How to Parse a JSON Object's Values into an ArrayList in Java?

How to Parse a JSON Object's Values into an ArrayList in Java?

Mary-Kate Olsen
Release: 2024-12-07 16:39:12
Original
502 people have browsed it

How to Parse a JSON Object's Values into an ArrayList in Java?

Parsing a JSON Object in Java: Extracting Values into an ArrayList

In this programming scenario, you encounter a JSON object and aim to parse its values into an array list in Java. The JSON object is structured as follows:

{
    "interests": [{
        "interestKey": "Dogs"
    }, {
        "interestKey": "Cats"
    }]
}
Copy after login

To address this task, you can utilize the org.json library. Here's a step-by-step solution:

  1. Create a JSON Object: First, you need to construct a JSON object from the given JSON string:

    JSONObject obj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");
    Copy after login
  2. Retrieve the Interests Array: Next, you need to extract the "interests" array from the JSON object:

    JSONArray array = obj.getJSONArray("interests");
    Copy after login
  3. Initialize an ArrayList: Now, create an ArrayList to store the interest keys:

    List<String> list = new ArrayList<String>();
    Copy after login
  4. Iterate Over the Interests Array: Utilize a loop to iterate through the interests array and extract the interest keys:

    for (int i = 0; i < array.length(); i++) {
        list.add(array.getJSONObject(i).getString("interestKey"));
    }
    Copy after login
  5. Retrieve the Parsed Values: The ArrayList now contains the interest keys from the JSON object:

    System.out.println(list); // Output: [Dogs, Cats]
    Copy after login

By following these steps, you can effectively parse the given JSON object in Java and populate an array list with its "interestKey" values.

The above is the detailed content of How to Parse a JSON Object's Values into an ArrayList 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