Iterating Through JSON Arrays in Android/Java
When interacting with web services or databases, it's common to receive data in JSON format. This data can be structured in hierarchical objects and arrays. Iterating through these data structures is crucial for extracting the information you need.
Specifically, you've inquired about iterating through a JSON array, which is represented as a collection of JSON objects enclosed in square brackets. To access the individual objects within this array, you can utilize the following steps:
1. Convert the JSON String to a JSON Array:
Assuming you have a JSON string containing the array, you can convert it to a JSON array using:
JSONArray array = new JSONArray(json_string);
2. Iterate Using a For Loop:
To loop through each JSON object in the array, you can use the following loop:
for (int i = 0; i < array.length(); i++) { JSONObject row = array.getJSONObject(i); int id = row.getInt("id"); String name = row.getString("name"); }
In this example, the row variable represents the individual JSON objects within the array. You can access their properties (e.g., "id" and "name") using the row.getXXX() methods.
Example:
JSONArray array = new JSONArray("[{ \"id\": 1, \"name\": \"John\" }, { \"id\": 2, \"name\": \"Jane\" }]"); for (int i = 0; i < array.length(); i++) { JSONObject row = array.getJSONObject(i); int id = row.getInt("id"); String name = row.getString("name"); System.out.println(id + ": " + name); }
Output:
1: John 2: Jane
This code effectively iterates through the JSON array, extracting the "id" and "name" values from each JSON object.
Remember, questions like these often require specific context and code samples. For more detailed scenarios, it's always advisable to provide code snippets and specific error messages encountered along the way.
The above is the detailed content of How Do I Iterate Through a JSON Array in Android/Java?. For more information, please follow other related articles on the PHP Chinese website!