Accessing Members of Items in a JSONArray with Java
When working with JSON data, it's often necessary to access specific values within JSON arrays. A JSONArray represents a list of JSON objects in a JSON document. This article will guide you on how to access and retrieve string values from within a JSONArray using Java.
Consider the following sample JSON:
{ "locations": { "record": [ { "id": 8817, "loc": "NEW YORK CITY" }, { "id": 2873, "loc": "UNITED STATES" }, { "id": 1501 "loc": "NEW YORK STATE" } ] } }
Once you have access to the record JSONArray, you can use the following steps to retrieve the "id" and "loc" values for each record:
Here's a sample code that demonstrates accessing the "id" and "loc" values:
import org.json.JSONArray; import org.json.JSONObject; ... // Load JSON data as before JSONArray recs = locs.getJSONArray("record"); for (int i = 0; i < recs.length(); ++i) { JSONObject rec = recs.getJSONObject(i); int id = rec.getInt("id"); String loc = rec.getString("loc"); // Process id and loc as needed... }
By following these steps, you can efficiently navigate and extract specific values from within a JSONArray, enabling you to consume and manipulate JSON data in your Java applications.
The above is the detailed content of How to Access Members of a JSONArray in Java?. For more information, please follow other related articles on the PHP Chinese website!