Home >Java >javaTutorial >How to Access and Extract Values from a Nested JSONArray in Java?
Accessing Member Values from a JSONArray in Java
Navigating through a JSONArray can be a challenge for those new to JSON parsing. Let's consider a scenario where you need to retrieve specific values from a nested JSON structure.
Suppose you have a JSON file with the following structure:
{ "locations": { "record": [ { "id": 8817, "loc": "NEW YORK CITY" }, { "id": 2873, "loc": "UNITED STATES" }, { "id": 1501, "loc": "NEW YORK STATE" } ] } }
Using Java's JSON parsing capabilities, you can access the "record" JSONArray using the following code:
JSONObject req = new JSONObject(join(loadStrings(data.json),"")); JSONObject locs = req.getJSONObject("locations"); JSONArray recs = locs.getJSONArray("record");
To iterate through the "record" JSONArray and extract the "id" and "loc" values, you can employ the following loop:
for (int i = 0; i < recs.length(); ++i) { JSONObject rec = recs.getJSONObject(i); int id = rec.getInt("id"); String loc = rec.getString("loc"); // ... }
Here's how each line of code contributes to the solution:
By combining these techniques, you'll be able to efficiently access and utilize the data within a JSONArray in your Java application.
The above is the detailed content of How to Access and Extract Values from a Nested JSONArray in Java?. For more information, please follow other related articles on the PHP Chinese website!