Oskar Alfons Oskar Alfons - 5 months ago 50
JSON Question

Jackson JSON: get node name from json-tree

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.

Answer

The JSON terms for what you're calling the "node name" is, I think, the key. Since JsonNode#iterator() does not include keys, you need to iterate a bit differently:

for (Map.Entry<String, JsonNode> elt : rootNode.fields()
{
    if ("foo".equals(elt.getKey())
    {
        // bar
    }
}

If you only need to see the keys, you can simplify things a bit with JsonNode#fieldNames():

for (String key : rootNode.fieldNames()
{
    if ("foo".equals(key)
    {
        // bar
    }
}

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:

JsonNode foo = rootNode.get("foo");
if (foo != null)
{
    // frob that widget
}
Comments