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}]}";
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")); }
This code performs the following steps:
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!