如何使用Jackson解析嵌套的JSON(无论是递归还是迭代)?

Pac*_*ver 2 java json jackson

我有一个示例JSON有效负载,如下所示:

 {"timestamp": 1427394360, "device": {"user-agent": "Mac OS 10.10.2 2.6 GHz Intel Core i7"}}
Run Code Online (Sandbox Code Playgroud)

我解析它并使用以下方法获取键/值对:

 Iterator<Map.Entry<String,JsonNode>> fieldsIterator = rootNode.fields();

 while (fieldsIterator.hasNext()) {
    Map.Entry<String,JsonNode> field = fieldsIterator.next();
    key = field.getKey();
    value = field.getValue();
    System.out.println("Key: " + key);
    System.out.println("Value: " + value);
 }
Run Code Online (Sandbox Code Playgroud)

这输出:

Key: timestamp
Value: 1427394360

Key: device
Value: {"user-agent": "Mac OS 10.10.2 2.6 GHz Intel Core i7"}
Run Code Online (Sandbox Code Playgroud)

如何设置它以便我可以解析设备密钥中的键/值对变为:

Key: "user-agent"
Value: "Mac OS 10.10.2 2.6 GHz Intel Core i7"
Run Code Online (Sandbox Code Playgroud)

而且,可能有JSON在其中包含更多嵌套的JSON ...意味着某些JSON可能没有嵌套的JSON,而有些可能有多个...

有没有办法使用Jackson以递归方式解析JSON有效负载中的所有键/值对?

感谢您抽出时间来阅读...

小智 5

如果值是容器(例如:数组或对象),则可以将代码放在方法中并进行递归调用.

例如:

public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    final JsonNode rootNode = mapper.readTree(" {\"timestamp\": 1427394360, \"device\": {\"user-agent\": \"Mac OS 10.10.2 2.6 GHz Intel Core i7\"}}");
    print(rootNode);
}

private static void print(final JsonNode node) throws IOException {
    Iterator<Map.Entry<String, JsonNode>> fieldsIterator = node.getFields();

    while (fieldsIterator.hasNext()) {
        Map.Entry<String, JsonNode> field = fieldsIterator.next();
        final String key = field.getKey();
        System.out.println("Key: " + key);
        final JsonNode value = field.getValue();
        if (value.isContainerNode()) {
            print(value); // RECURSIVE CALL
        } else {
            System.out.println("Value: " + value);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)