Get all the keys in a JSON string JsonNode in java
forEach
will iterate over children of a JsonNode
(converted to String
when printed) and fieldNames()
gets an Iterator<String>
over keys. Here are some examples for printing elements of the example 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);
You'll probably need fields()
at some point that returns an Iterator<Entry<String, JsonNode>>
so you can iterate over key, value pairs.
This should do it.
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;
}
This will print out result as
[required, requiredMsg, choices, exc, a, b, c, required, textbox, d, choiceSettings, type, Settings]
The accepted answer works out great but issues a warning, "Type safety: The expression of type Map
needs unchecked conversion to conform to Map <String, Object>
"
This answer led me to change that line to the following to eliminate the warning:
Map<String, Object> treeMap = mapper.readValue(json, new TypeReference<Map<String, Object>>() {});