Hutool 的 JSONArray 类实现了 Iterable 接口,因此你可以使用 Java 8 引入的 forEach 方法来遍历它。
以下是一个使用 forEach 遍历 JSONArray 的示例:
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
public class HutoolExample {
public static void main(String[] args) {
// 示例JSON字符串
String jsonString = "[{\"name\":\"John\",\"age\":30},{\"name\":\"Jane\",\"age\":25}]";
// 使用Hutool的getJSONArray方法获取JSON数组
JSONArray jsonArray = JSONUtil.getJSONArray(jsonString);
// 使用forEach遍历数组中的每个元素
jsonArray.forEach(obj -> {
JSONObject jsonObject = (JSONObject) obj;
String name = jsonObject.getStr("name");
int age = jsonObject.getInt("age");
System.out.println("Name: " + name + ", Age: " + age);
});
}
}