java 递归解析json_Java递归解析任意层的Json数据,获取所有的key和value,
时间: 2024-03-20 11:42:30 浏览: 105
好的,这个问题需要用到JSON解析库和递归算法。我推荐使用Jackson作为JSON解析库,以下是一个Java递归解析任意层的JSON数据的示例代码:
```java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Iterator;
public class JsonParser {
public static void parseJson(String jsonStr) throws Exception {
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(jsonStr);
parseNode(rootNode, "");
}
private static void parseNode(JsonNode node, String prefix) {
if (node.isObject()) {
Iterator<String> fieldNames = node.fieldNames();
while (fieldNames.hasNext()) {
String fieldName = fieldNames.next();
JsonNode childNode = node.get(fieldName);
String newPrefix = prefix.isEmpty() ? fieldName : prefix + "." + fieldName;
parseNode(childNode, newPrefix);
}
} else if (node.isArray()) {
for (int i = 0; i < node.size(); i++) {
JsonNode childNode = node.get(i);
String newPrefix = prefix.isEmpty() ? "[" + i + "]" : prefix + "[" + i + "]";
parseNode(childNode, newPrefix);
}
} else {
System.out.println(prefix + " = " + node.asText());
}
}
}
```
调用示例:
```java
String jsonStr = "{\"name\":\"John Smith\",\"age\":30,\"address\":{\"street\":\"123 Main St\",\"city\":\"New York\"},\"phoneNumbers\":[{\"type\":\"home\",\"number\":\"555-555-1234\"},{\"type\":\"work\",\"number\":\"555-555-5678\"}]}";
JsonParser.parseJson(jsonStr);
```
输出结果:
```
name = John Smith
age = 30
address.street = 123 Main St
address.city = New York
phoneNumbers[0].type = home
phoneNumbers[0].number = 555-555-1234
phoneNumbers[1].type = work
phoneNumbers[1].number = 555-555-5678
```
阅读全文