在Java中获取JSON字符串JsonNode中的所有键

Sen*_*mas 4 java json jackson

我有一个json字符串,我需要验证并找到除json字符串中的列表以外的其他任何键。样本json字符串是

{
   "required" : true,
   "requiredMsg" : "Title needed",
   "choices" : [ "a", "b", "c", "d" ],
   "choiceSettings" : {
          "a" : {
          "exc" : true
      },
  "b" : { },
  "c" : { },
  "d" : {
  "textbox" : {
    "required" : true
  }
 }
},
"Settings" : {
"type" : "none"
}
}
Run Code Online (Sandbox Code Playgroud)

为了只允许预定义的键存在于json字符串中,我想获取json字符串中的所有键。如何获取json字符串中的所有键。我正在使用jsonNode。到目前为止,我的代码是

        JsonNode rootNode = mapper.readTree(option);
        JsonNode reqiredMessage = rootNode.path("reqiredMessage");             
        System.out.println("msg   : "+  reqiredMessage.asText());            
        JsonNode drNode = rootNode.path("choices");
        Iterator<JsonNode> itr = drNode.iterator();
        System.out.println("\nchoices:");
        while (itr.hasNext()) {
            JsonNode temp = itr.next();
            System.out.println(temp.asText());
        }    
Run Code Online (Sandbox Code Playgroud)

如何使用JSON字符串获取所有键 JsonNode

Man*_*dis 6

forEach将遍历一个的子项JsonNodeString在打印时转换为)并fieldNames()获得一个Iterator<String>over键。以下是一些打印示例JSON元素的示例:

JsonNode rootNode = mapper.readTree(option);

System.out.println("\nchoices:");
rootNode.path("choices").forEach(System.out::println);

System.out.println("\nAllKeys:");
rootNode.fieldNames().forEachRemaining(System.out::println);

System.out.println("\nChoiceSettings:");
rootNode.path("choiceSettings").fieldNames().forEachRemaining(System.out::println);
Run Code Online (Sandbox Code Playgroud)

您可能需要fields()在某个时候返回an,Iterator<Entry<String, JsonNode>>以便可以遍历键,值对。


pvp*_*ran 6

这应该这样做。

Map<String, Object> treeMap = mapper.readValue(json, Map.class);

List<String> keys  = Lists.newArrayList();
List<String> result = findKeys(treeMap, keys);
System.out.println(result);

private List<String> findKeys(Map<String, Object> treeMap , List<String> keys) {
    treeMap.forEach((key, value) -> {
      if (value instanceof LinkedHashMap) {
        Map<String, Object> map = (LinkedHashMap) value;
        findKeys(map, keys);
      }
      keys.add(key);
    });

    return keys;
  }
Run Code Online (Sandbox Code Playgroud)

这将打印出结果为

[required, requiredMsg, choices, exc, a, b, c, required, textbox, d, choiceSettings, type, Settings]
Run Code Online (Sandbox Code Playgroud)