在Java中获取JSON字符串JsonNode中的所有键 [英] Get all the keys in a JSON string JsonNode in java
本文介绍了在Java中获取JSON字符串JsonNode中的所有键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个json字符串,我需要验证并找到除json字符串中的列表以外的其他任何键.样本json字符串是
I have a json string which I need to validate and find any other keys other than in a list is there in the json string. The sample json string is
{
"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.到目前为止,我的代码是
To allow only predifined keys is exsist in the json string I want to get all the keys in the json string. How can I obtain all the keys in the json string. I am using jsonNode. My code till now is
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
推荐答案
这应该可以做到.
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]
这篇关于在Java中获取JSON字符串JsonNode中的所有键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文