How to iterate through objects in a JSONArray in Java?
You can use the following method to iterate through objects in a JSONArray in Java.
import org.json.JSONArray;
import org.json.JSONObject;
// 假设jsonArray是JSONArray对象
JSONArray jsonArray = new JSONArray("[{\"name\":\"Alice\",\"age\":25},{\"name\":\"Bob\",\"age\":30}]");
// 遍历JSONArray中的对象
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// 获取对象中的属性值
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
System.out.println("Name: " + name + ", Age: " + age);
}
In the above code, we first create a JSONArray object, then use the getJSONObject() method to retrieve each JSONObject object within the JSONArray, and finally use the getString() and getInt() methods to obtain the values of the properties within the objects.
This method allows you to iterate through the objects in a JSONArray and retrieve their attribute values.