在Java开发中,JSON(JavaScript Object Notation)作为一种轻量级的数据交换格式,被广泛应用于前后端数据交互、配置文件存储等场景,对JSON数据进行遍历是处理JSON数据的基础操作,本文将详细介绍Java中遍历JSON的多种方法,涵盖不同JSON库的使用场景及代码示例。

使用org.json库遍历JSON
org.json是一个简单易用的JSON处理库,适用于轻量级JSON操作,首先需要添加依赖(Maven):
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20231013</version>
</dependency>
遍历JSON对象
JSON对象在org.json中对应JSONObject类,通过keySet()方法获取所有键,再遍历键值对:
import org.json.JSONObject;
public class JSONObjectTraversal {
public static void main(String[] args) {
String jsonStr = "{\"name\":\"Alice\",\"age\":25,\"city\":\"New York\"}";
JSONObject jsonObject = new JSONObject(jsonStr);
// 遍历键值对
for (String key : jsonObject.keySet()) {
Object value = jsonObject.get(key);
System.out.println("Key: " + key + ", Value: " + value);
}
}
}
遍历JSON数组
JSON数组对应JSONArray类,通过length()获取长度,再通过索引遍历:
import org.json.JSONArray;
public class JSONArrayTraversal {
public static void main(String[] args) {
String jsonArrayStr = "[{\"name\":\"Bob\"},{\"name\":\"Charlie\"}]";
JSONArray jsonArray = new JSONArray(jsonArrayStr);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println("Name: " + jsonObject.getString("name"));
}
}
}
使用Gson库遍历JSON
Gson是Google推出的JSON处理库,支持将JSON与Java对象相互转换,适合复杂对象的遍历,添加依赖:

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
将JSON转换为Map遍历
通过Gson的fromJson()方法将JSON字符串转换为Map,再遍历Map:
import com.google.gson.Gson;
import java.util.Map;
public class GsonMapTraversal {
public static void main(String[] args) {
String jsonStr = "{\"name\":\"David\",\"age\":30}";
Gson gson = new Gson();
Map<String, Object> map = gson.fromJson(jsonStr, Map.class);
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
遍历嵌套JSON对象
对于嵌套结构,可递归遍历:
public class GsonNestedTraversal {
public static void main(String[] args) {
String nestedJson = "{\"user\":{\"name\":\"Eve\",\"details\":{\"age\":28,\"city\":\"London\"}}}";
Gson gson = new Gson();
Map<String, Object> map = gson.fromJson(nestedJson, Map.class);
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getValue() instanceof Map) {
System.out.println("Key: " + entry.getKey());
traverseMap((Map<String, Object>) entry.getValue());
} else {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
private static void traverseMap(Map<String, Object> map) {
for (Map.Entry<String, Object> innerEntry : map.entrySet()) {
if (innerEntry.getValue() instanceof Map) {
System.out.println(" " + innerEntry.getKey());
traverseMap((Map<String, Object>) innerEntry.getValue());
} else {
System.out.println(" " + innerEntry.getKey() + ": " + innerEntry.getValue());
}
}
}
}
使用Jackson库遍历JSON
Jackson是高性能的JSON处理库,提供了灵活的遍历方式,添加依赖:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
使用JsonNode遍历
JsonNode是Jackson的核心类,支持树形遍历:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTraversal {
public static void main(String[] args) throws Exception {
String jsonStr = "{\"name\":\"Frank\",\"hobbies\":[\"reading\",\"swimming\"]}";
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(jsonStr);
// 遍历字段
rootNode.fields().forEachRemaining(entry -> {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
});
// 遍历数组
JsonNode hobbiesNode = rootNode.get("hobbies");
if (hobbiesNode != null && hobbiesNode.isArray()) {
for (JsonNode hobby : hobbiesNode) {
System.out.println("Hobby: " + hobby.asText());
}
}
}
}
递归遍历复杂结构
public class JacksonRecursiveTraversal {
public static void main(String[] args) throws Exception {
String complexJson = "{\"data\":{\"users\":[{\"id\":1,\"name\":\"Grace\"},{\"id\":2,\"name\":\"Henry\"}]}}";
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(complexJson);
traverseNode(rootNode, 0);
}
private static void traverseNode(JsonNode node, int level) {
if (node.isObject()) {
node.fields().forEachRemaining(entry -> {
indent(level);
System.out.println("Key: " + entry.getKey());
traverseNode(entry.getValue(), level + 1);
});
} else if (node.isArray()) {
for (JsonNode arrayNode : node) {
traverseNode(arrayNode, level + 1);
}
} else {
indent(level);
System.out.println("Value: " + node.asText());
}
}
private static void indent(int level) {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
}
}
遍历JSON的注意事项
- 异常处理:JSON解析可能抛出
JSONException(org.json)、JsonSyntaxException(Gson)或JsonProcessingException(Jackson),需进行捕获处理。 - 数据类型转换:遍历时需注意JSON数据类型与Java类型的对应关系,如
null值需通过isNull()方法判断。 - 性能考虑:对于大型JSON文件,建议使用流式解析(如Jackson的
JsonParser),避免内存溢出。 - 安全性:避免直接解析不可信的JSON数据,防止注入攻击。
Java中遍历JSON数据可根据项目需求选择合适的库:org.json适合轻量级操作,Gson和Jackson则更适合复杂对象和大规模数据处理,掌握不同库的遍历方式,能更高效地处理JSON数据,提升开发效率,在实际应用中,需结合异常处理、性能优化等因素,确保代码的健壮性和可维护性。

















