Home >Java >javaTutorial >How to Parse a JSON Object and Store Specific Keys in an ArrayList Using Java?

How to Parse a JSON Object and Store Specific Keys in an ArrayList Using Java?

Linda Hamilton
Linda HamiltonOriginal
2024-12-05 11:05:151042browse

How to Parse a JSON Object and Store Specific Keys in an ArrayList Using Java?

Parsing JSON Objects in Java

Many JSON parsing frameworks are available in Java, allowing developers to work with JSON data conveniently. This question revolves around parsing a specific JSON object structure and storing interest keys in an array list.

To achieve this using the org.json library:

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

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

List<String> list = new ArrayList<>();
JSONArray array = obj.getJSONArray("interests");
for(int i = 0 ; i < array.length() ; i++){
    list.add(array.getJSONObject(i).getString("interestKey"));
}
  1. Create a new JSONObject instance using the string representation of JSON provided.
  2. Obtain the JSONArray named "interests" from the object.
  3. Loop through the array and for each element, retrieve the interestKey as a string.
  4. Add the retrieved interestKey to an ArrayList.

This approach will effectively store all the interestKeys in an array list, providing easy access and manipulation within the Java code.

The above is the detailed content of How to Parse a JSON Object and Store Specific Keys in an ArrayList Using 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