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
Barbara StreisandOriginal
2024-12-07 08:15:14895browse

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}]}";

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}]}");
  1. Extract the nested array as a JSONArray:
JSONArray array = obj.getJSONArray("interests");
  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"));
}

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!

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