Home >Java >javaTutorial >How to Extract Interest Keys from a JSON Object in Java?

How to Extract Interest Keys from a JSON Object in Java?

Susan Sarandon
Susan SarandonOriginal
2024-12-07 01:03:15363browse

How to Extract Interest Keys from a JSON Object in Java?

Retrieving Interest Keys from a JSON Object in Java

As outlined in your query, you aim to parse a JSON object containing a list of interests into an arraylist in Java. Here's a step-by-step guide to achieve this using the org.json library:

1. Import the org.json Library:

import org.json.JSONObject;
import org.json.JSONArray;

2. Create an instance of JSONObject:

JSONObject obj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");

3. Create an ArrayList for Interest Keys:

List<String> list = new ArrayList<String>();

4. Extract the "interests" Array:

JSONArray array = obj.getJSONArray("interests");

5. Iterate Through the Array and Extract Interest Keys:

for (int i = 0; i < array.length(); i++) {
    list.add(array.getJSONObject(i).getString("interestKey"));
}

Result:

The resulting ArrayList, list, will contain all the interest keys in the original JSON object.

The above is the detailed content of How to Extract Interest Keys from a JSON Object 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