在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);
});
以上是三種常見(jiàn)的遍歷JSONArray的方法,在實(shí)際應(yīng)用中可以根據(jù)具體需求選擇合適的方法來(lái)遍歷JSONArray中的元素。