在Java中遍历JSON对象
在Java中遍历JSON对象通常需要使用JSON处理库,如org.json、Gson或Jackson,以下是几种常见方法的示例:
使用 org.json 库
import org.json.JSONObject;
public class JsonTraversal {
public static void main(String[] args) {
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
JSONObject jsonObject = new JSONObject(jsonString);
// 方法1: 使用keys()遍历键
System.out.println("方法1 - 使用keys():");
for (String key : jsonObject.keySet()) {
Object value = jsonObject.get(key);
System.out.println(key + ": " + value);
}
// 方法2: 使用entrySet()遍历
System.out.println("\n方法2 - 使用entrySet():");
for (String key : jsonObject.keySet()) {
System.out.println(key + ": " + jsonObject.get(key));
}
}
}
使用 Gson 库
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class GsonTraversal {
public static void main(String[] args) {
String jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
// 遍历所有键值对
System.out.println("使用Gson遍历:");
for (String key : jsonObject.keySet()) {
System.out.println(key + ": " + jsonObject.get(key));
}
}
}
使用 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 jsonString = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(jsonString);
// 遍历所有字段
System.out.println("使用Jackson遍历:");
rootNode.fields().forEachRemaining(entry -> {
System.out.println(entry.getKey() + ": " + entry.getValue());
});
}
}
递归遍历嵌套JSON对象
如果需要处理嵌套的JSON对象,可以使用递归方法:
import org.json.JSONObject;
public class NestedJsonTraversal {
public static void main(String[] args) {
String jsonString = "{\"person\":{\"name\":\"John\", \"age\":30}, \"address\":{\"city\":\"New York\"}}";
JSONObject jsonObject = new JSONObject(jsonString);
System.out.println("递归遍历嵌套JSON:");
traverseJson(jsonObject, "");
}
public static void traverseJson(JSONObject json, String indent) {
for (String key : json.keySet()) {
Object value = json.get(key);
System.out.println(indent + key + ":");
if (value instanceof JSONObject) {
traverseJson((JSONObject) value, indent + " ");
} else {
System.out.println(indent + " " + value);
}
}
}
}
注意事项
-
确保在项目中添加相应的JSON库依赖:
- org.json:
implementation 'org.json:json:20251013' - Gson:
implementation 'com.google.code.gson:gson:2.10.1' - Jackson:
implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2'
- org.json:
-
处理JSON时要注意异常处理,特别是当JSON结构可能不符合预期时。
-
对于大型JSON文件,考虑使用流式API(如Jackson的JsonParser)以提高性能。
-
如果需要处理JSON数组,可以使用类似的方法,但使用
JSONArray代替JSONObject。
