在Java中遍历JSONArray可以使用以下几种方法:
JSONArray jsonArray = new JSONArray("[{\"name\":\"John\",\"age\":30},{\"name\":\"Jane\",\"age\":25}]");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
String name = jsonObj.getString("name");
int age = jsonObj.getInt("age");
System.out.println("Name: " + name + ", Age: " + age);
}
JSONArray jsonArray = new JSONArray("[{\"name\":\"John\",\"age\":30},{\"name\":\"Jane\",\"age\":25}]");
Iterator<Object> iterator = jsonArray.iterator();
while (iterator.hasNext()) {
JSONObject jsonObj = (JSONObject) iterator.next();
String name = jsonObj.getString("name");
int age = jsonObj.getInt("age");
System.out.println("Name: " + name + ", Age: " + age);
}
JSONArray jsonArray = new JSONArray("[{\"name\":\"John\",\"age\":30},{\"name\":\"Jane\",\"age\":25}]");
jsonArray.forEach(item -> {
JSONObject jsonObj = (JSONObject) item;
String name = jsonObj.getString("name");
int age = jsonObj.getInt("age");
System.out.println("Name: " + name + ", Age: " + age);
});
以上是三种常见的遍历JSONArray的方法,在实际应用中可以根据具体需求选择合适的方法来遍历JSONArray中的元素。