How can I receive the node names from a JSON tree using Jackson?
The JSON-File looks something like this:
{
node1:"value1",
node2:"value2",
node3:{
node3.1:"value3.1",
node3.2:"value3.2"
}
}
I have
JsonNode rootNode = mapper.readTree(fileReader);
and need something like
for (JsonNode node : rootNode){
if (node.getName().equals("foo"){
//bar
}
}
thanks.
This answer applies to Jackson versions prior to 2+ (originally written for 1.8). See @SupunSameera’s answer for a version that works with newer versions of Jackson.
The JSON terms for “node name” is “key.” Since
JsonNode#iterator()does not include keys, you need to iterate differently:
If you only need to see the keys, you can simplify things a bit with
JsonNode#fieldNames():And if you just want to find the node with key
"foo", you can access it directly. This will yield better performance (constant-time lookup) and cleaner/clearer code than using a loop: