Accessing "id" and "loc" Values from a Nested JSONArray in Java
When parsing JSON data in Java, it's common to encounter nested structures, such as JSONArrays within JSONObjects. Accessing specific values within these nested structures can be a bit tricky for beginners.
Problem:
Consider the following JSON data:
{ "locations": { "record": [ { "id": 8817, "loc": "NEW YORK CITY" }, { "id": 2873, "loc": "UNITED STATES" }, { "id": 1501, "loc": "NEW YORK STATE" } ] } }
The goal is to iterate through the "record" JSONArray and access the "id" and "loc" values for each record.
Solution:
To access the members of an item in a JSONArray, you can use the getJSONObject(int) method. The following code demonstrates how to achieve this:
JSONObject req = new JSONObject(join(loadStrings(data.json),"")); JSONObject locs = req.getJSONObject("locations"); 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"); // ... }
Within the for-loop:
These retrieved values can then be used for further processing or operations.
The above is the detailed content of How to Extract \'id\' and \'loc\' Values from a Nested JSONArray in Java?. For more information, please follow other related articles on the PHP Chinese website!