我有一个 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字符串中的所有键值
最佳答案
forEach
将遍历 JsonNode
的 child (打印时转换为 String
)和 fieldNames()
得到一个 Iterator<String>
在 key 上。以下是打印示例 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>>
这样您就可以遍历键值对。
关于java - 在java中获取JSON字符串JsonNode中的所有键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48785312/