[英]Get all the keys in a JSON string JsonNode in java
我有一個 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
子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>>
以便您可以迭代鍵值對。
這應該做。
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]
接受的答案效果很好,但會發出警告,“類型安全:類型Map
的表達式需要未經檢查的轉換以符合Map <String, Object>
”
這個答案使我將該行更改為以下內容以消除警告:
Map<String, Object> treeMap = mapper.readValue(json, new TypeReference<Map<String, Object>>() {});
接受的解決方案不支持 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.