代码生成(用java使用ObjectMapper遍历每一种类型的节点)
时间: 2023-12-17 07:04:08 浏览: 82
以下是使用 Java 中的 ObjectMapper 遍历节点的示例代码:
```java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonTraversal {
public static void main(String[] args) throws Exception {
String jsonString = "{\n" +
" \"name\": \"John\",\n" +
" \"age\": 30,\n" +
" \"isMarried\": true,\n" +
" \"hobbies\": [\n" +
" \"reading\",\n" +
" \"programming\"\n" +
" ],\n" +
" \"address\": {\n" +
" \"street\": \"123 Main St\",\n" +
" \"city\": \"New York\",\n" +
" \"state\": \"NY\",\n" +
" \"zip\": \"10001\"\n" +
" }\n" +
"}";
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(jsonString);
traverse(rootNode);
}
private static void traverse(JsonNode node) {
if (node.isObject()) {
System.out.println("Object node: " + node);
node.fields().forEachRemaining(entry -> {
System.out.println("Key: " + entry.getKey());
traverse(entry.getValue());
});
} else if (node.isArray()) {
System.out.println("Array node: " + node);
node.elements().forEachRemaining(JsonTraversal::traverse);
} else if (node.isValueNode()) {
System.out.println("Value node: " + node);
}
}
}
```
在此示例中,我们首先将 JSON 字符串转换为 `JsonNode` 树,然后递归地遍历树中的每个节点。对于对象节点,我们遍历对象中的每个键值对,并对其值递归调用 `traverse` 方法。对于数组节点,我们遍历数组中的每个元素,并对其递归调用 `traverse` 方法。对于值节点,我们仅打印节点本身。
输出如下:
```
Object node: {"name":"John","age":30,"isMarried":true,"hobbies":["reading","programming"],"address":{"street":"123 Main St","city":"New York","state":"NY","zip":"10001"}}
Key: name
Value node: "John"
Key: age
Value node: 30
Key: isMarried
Value node: true
Key: hobbies
Array node: ["reading","programming"]
Value node: "reading"
Value node: "programming"
Key: address
Object node: {"street":"123 Main St","city":"New York","state":"NY","zip":"10001"}
Key: street
Value node: "123 Main St"
Key: city
Value node: "New York"
Key: state
Value node: "NY"
Key: zip
Value node: "10001"
```
阅读全文