Parsing a JSON Object in Java: Extracting Values into an ArrayList
In this programming scenario, you encounter a JSON object and aim to parse its values into an array list in Java. The JSON object is structured as follows:
{ "interests": [{ "interestKey": "Dogs" }, { "interestKey": "Cats" }] }
To address this task, you can utilize the org.json library. Here's a step-by-step solution:
Create a JSON Object: First, you need to construct a JSON object from the given JSON string:
JSONObject obj = new JSONObject("{interests : [{interestKey:Dogs}, {interestKey:Cats}]}");
Retrieve the Interests Array: Next, you need to extract the "interests" array from the JSON object:
JSONArray array = obj.getJSONArray("interests");
Initialize an ArrayList: Now, create an ArrayList to store the interest keys:
List<String> list = new ArrayList<String>();
Iterate Over the Interests Array: Utilize a loop to iterate through the interests array and extract the interest keys:
for (int i = 0; i < array.length(); i++) { list.add(array.getJSONObject(i).getString("interestKey")); }
Retrieve the Parsed Values: The ArrayList now contains the interest keys from the JSON object:
System.out.println(list); // Output: [Dogs, Cats]
By following these steps, you can effectively parse the given JSON object in Java and populate an array list with its "interestKey" values.
The above is the detailed content of How to Parse a JSON Object's Values into an ArrayList in Java?. For more information, please follow other related articles on the PHP Chinese website!