Jackson JSON: get node name from json-tree

JavaJsonJackson

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

For Jackson 2+ (com.fasterxml.jackson), the methods are little bit different:

Iterator<Entry<String, JsonNode>> nodes = rootNode.get("foo").fields();

while (nodes.hasNext()) {
  Map.Entry<String, JsonNode> entry = (Map.Entry<String, JsonNode>) nodes.next();

  logger.info("key --> " + entry.getKey() + " value-->" + entry.getValue());
}

Solution 2 - Java

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:

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
}

Solution 3 - Java

fields() and fieldNames() both were not working for me. And I had to spend quite sometime to find a way to iterate over the keys. There are two ways by which it can be done.

One is by converting it into a map (takes up more space):

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> result = mapper.convertValue(jsonNode, Map.class);
for (String key : result.keySet())
{
    if(key.equals(foo))
    {
        //code here
    }
}

Another, by using a String iterator:

Iterator<String> it = jsonNode.getFieldNames();
while (it.hasNext())
{
	String key = it.next();
	if (key.equals(foo))
    {
         //code here
    }
}

Solution 4 - Java

Clarification Here:

While this will work:

 JsonNode rootNode = objectMapper.readTree(file);
 Iterator<Map.Entry<String, JsonNode>> fields = rootNode.fields();
 while (fields.hasNext()) {
	Map.Entry<String, JsonNode> entry = fields.next();
	log.info(entry.getKey() + ":" + entry.getValue())
 }

This will not:

JsonNode rootNode = objectMapper.readTree(file);

while (rootNode.fields().hasNext()) {
	Map.Entry<String, JsonNode> entry = rootNode.fields().next();
	log.info(entry.getKey() + ":" + entry.getValue())
}

So be careful to declare the Iterator as a variable and use that.

Be sure to use the fasterxml library rather than codehaus.

Solution 5 - Java

JsonNode root = mapper.readTree(json);
root.at("/some-node").fields().forEachRemaining(e -> {
    				          System.out.println(e.getKey()+"---"+ e.getValue());

		});

In one line Jackson 2+

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOskar AlfonsView Question on Stackoverflow
Solution 1 - JavaSupun SameeraView Answer on Stackoverflow
Solution 2 - JavaMatt BallView Answer on Stackoverflow
Solution 3 - JavaAnna ShekhawatView Answer on Stackoverflow
Solution 4 - JavaChrisGeoView Answer on Stackoverflow
Solution 5 - JavanashView Answer on Stackoverflow