可使用以下方法遍历 JSON 数组:Jackson 库:使用 ObjectMapper 读取 JSON 字符串并遍历 ArrayNode。TreeWalker:使用 TreeTraverser 遍历 ArrayNode。JSONObject 库:使用 JSONArray 获取数组并遍历。Gson 库:使用 JsonArray 解析 JSON 字符串并遍历元素。

如何在 Java 中遍历 JSON 数组
Jackson库
- 使用ObjectMapper
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(jsonStr);
if (rootNode.isArray()) {
for (JsonNode node : rootNode) {
// 处理数组中的每个元素
}
}- 使用TreeWalker
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.TreeTraverser;
TreeTraverser traverser = new TreeTraverser();
ArrayNode arrayNode = (ArrayNode) traverser.root(rootNode);
for (JsonNode node : arrayNode) {
// 处理数组中的每个元素
}JSONObject库
- 使用JSONArray
import org.json.JSONArray;
import org.json.JSONObject;
JSONObject obj = new JSONObject(jsonStr);
JSONArray array = obj.getJSONArray("key");
for (int i = 0; i < array.length(); i++) {
// 处理数组中的每个元素
}Gson库
立即学习“Java免费学习笔记(深入)”;
- 使用JsonArray
import com.google.gson.Gson;
import com.google.gson.JsonArray;
Gson gson = new Gson();
JsonArray array = gson.fromJson(jsonStr, JsonArray.class);
for (JsonElement element : array) {
// 处理数组中的每个元素
}











