Home > Java > javaTutorial > How to Parse a Nested JSON Array and Store Keys in an ArrayList in Java?

How to Parse a Nested JSON Array and Store Keys in an ArrayList in Java?

Barbara Streisand
Release: 2024-12-07 08:15:14
Original
845 people have browsed it

How to Parse a Nested JSON Array and Store Keys in an ArrayList in Java?

Parsing JSON Object in Java

This question seeks to parse a JSON object with a nested array of interest keys, and store the keys in an ArrayList. The sample JSON object provided is as follows:

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

To parse this JSON object in Java using the org.json library, follow these steps:

  1. Create a JSONObject object from the JSON string:
JSONObject obj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");
Copy after login
  1. Extract the nested array as a JSONArray:
JSONArray array = obj.getJSONArray("interests");
Copy after login
  1. Iterate through the array and extract the interest keys:
List<String> list = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
    list.add(array.getJSONObject(i).getString("interestKey"));
}
Copy after login

This approach will store the interest keys in an ArrayList. Note that the org.json library is an external dependency that may need to be added to your project before using it.

The above is the detailed content of How to Parse a Nested JSON Array and Store Keys in 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