Accessing JSON Array Objects in Java
Accessing string values within a JSONArray in Java requires understanding how to navigate the JSON structure and retrieve the desired data.
Given a JSON object like the one provided:
{ "locations": { "record": [ { "id": 8817, "loc": "NEW YORK CITY" }, { "id": 2873, "loc": "UNITED STATES" }, { "id": 1501 "loc": "NEW YORK STATE" } ] } }
To access the "id" and "loc" values in a for loop, use the following code:
JSONArray recs = req.getJSONObject("locations").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 the data as needed) }
This code iterates through the records array, accessing each record as a JSON object. It then retrieves the "id" value as an integer using getInt("id") and the "loc" value as a string using getString("loc"). The processed data can then be used in subsequent operations.
The above is the detailed content of How Do I Access and Process JSON Array Objects in Java?. For more information, please follow other related articles on the PHP Chinese website!