Home > Java > javaTutorial > How to Extract Array Elements from a JSON Object in Java?

How to Extract Array Elements from a JSON Object in Java?

Linda Hamilton
Release: 2024-12-04 16:04:15
Original
276 people have browsed it

How to Extract Array Elements from a JSON Object in Java?

Extracting Array Elements from JSON in Java

Parsing JSON data into accessible Java objects can be a challenge, especially when dealing with nested structures. Consider the task of extracting interest keys from a JSON object like this:

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

To achieve this in Java, we can leverage the power of the org.json library. Let's dive into the code:

import org.json.JSONObject;
import org.json.JSONArray;
import java.util.List;
import java.util.ArrayList;

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

List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("interests");
for(int i = 0 ; i < array.length() ; i++){
    list.add(array.getJSONObject(i).getString("interestKey"));
}
Copy after login

This code performs the following steps:

  1. Creates a new JSONObject object from the provided JSON string.
  2. Retrieves the "interests" array from the JSON object as a JSONArray object.
  3. Iterates through the JSONArray and extracts the "interestKey" string from each JSONObject.
  4. Adds the extracted "interestKey" string to a list of strings.

The above is the detailed content of How to Extract Array Elements 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