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
Release: 2024-12-07 01:03:15
Original
330 people have browsed it

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

2. Create an instance of JSONObject:

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

3. Create an ArrayList for Interest Keys:

List<String> list = new ArrayList<String>();
Copy after login

4. Extract the "interests" Array:

JSONArray array = obj.getJSONArray("interests");
Copy after login

5. Iterate Through the Array and Extract Interest Keys:

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

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!

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