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

时间:2018-02-14 10:49:52

标签: 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"
}
}

为了只允许预定义的密钥在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());
        }    

如何使用JsonNode

从json字符串中获取所有键

4 个答案:

答案 0 :(得分:4)

forEach将迭代JsonNode的子项(打印时转换为String),fieldNames()获得Iterator<String>个键。以下是打印示例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);

在某些时候你可能需要fields()返回一个Iterator<Entry<String, JsonNode>>,这样你就可以遍历键值对。

答案 1 :(得分:2)

可接受的答案非常有用,但会发出警告,“类型安全:类型Map的表达式需要未经检查的转换才能符合Map <String, Object>

This answer使我将该行更改为以下内容,以消除警告:

Map<String, Object> treeMap = mapper.readValue(json, new TypeReference<Map<String, Object>>() {}); 

答案 2 :(得分:1)

这应该这样做。

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

这将打印出结果

[required, requiredMsg, choices, exc, a, b, c, required, textbox, d, choiceSettings, type, Settings]

答案 3 :(得分:0)

已接受的解决方案不支持 json 中的列表。这是我的建议:

public List<String> getAllNodeKeys(String json) throws JsonProcessingException {
    Map<String, Object> treeMap = objectMapper.readValue(json, new TypeReference<>() {
    });
    return findKeys(treeMap, new ArrayList<>());
}

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

        }
        keys.add(key);
    });

    return keys;
}