2015-04-04 119 views
1

我有一个样品JSON有效载荷,看起来像这样:使用此键/值对如何使用Jackson解析嵌套的JSON(无论是递归还是迭代)?

{"timestamp": 1427394360, "device": {"user-agent": "Mac OS 10.10.2 2.6 GHz Intel Core i7"}} 

我分析它,并获得:

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); 
} 

此输出:

Key: timestamp 
Value: 1427394360 

Key: device 
Value: {"user-agent": "Mac OS 10.10.2 2.6 GHz Intel Core i7"} 

我如何设置它,以便我可以解析出设备密钥内的键/值对,以便成为:

Key: "user-agent" 
Value: "Mac OS 10.10.2 2.6 GHz Intel Core i7" 

而且也有可能是JSON有里面更加嵌套JSON ...... 这意味着有些JSON可能没有嵌套JSON和一些可能有多个...

有没有一种办法使用Jackson递归地解析JSON负载中的所有键/值对?

感谢您在百忙之中阅读本文时...

+0

键“device”对应的“value”是一个Map。你可以像对待包含Map一样对待它。 – 2015-04-04 01:53:55

+0

有没有办法在做这个之前检查是否有地图? – 2015-04-04 02:55:41

+0

'instanceof',也许? – 2015-04-04 02:58:03

回答

3

你可以把你的代码的方法并进行递归调用,如果该值是容器(例如:数组或对象)。

例如:

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); 
     } 
    } 
}