2015-04-04 116 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); 
     } 
    } 
}