Jackson json : traversing a json tree node by node

13,285

Solution 1

You can simple use JsonNode.iterator() method to get all subnodes of a node (to a level you need). You can check if a node JsonNode.isArray or JsonNode.isObject or any other type in order to stop deep-first search. Everything else you need is just related to trees traversal.

Solution 2

If you just want to compare t1 and t2, you can write as simple as t1.equals(t2). I assume that t1 and t2 are JsonNode type which has implemented the equals method.

Solution 3

 boolean NodesEqual(JsonNode n1, JsonNode n2) {
  if(n1.size()!=n2.size())return false;
  // ... other equality checks, like name, data type, etc
  for(int i=0;i<n.size();i++){
    JsonNode child1 = n1.get(i);
    JsonNode child2 = n2.get(i);
    if(!NodesEqual(child1,child2)) return false;
  } 
  return true;
 }

This is a recursive, so massive, or deeply nested documents may have problems, but this should work fine for the normal cases.

Share:
13,285
athreya86
Author by

athreya86

Updated on September 15, 2022

Comments

  • athreya86
    athreya86 almost 2 years

    I have numerous text files containing json data and I'm using new ObjectMapper().readTree() method in Jackson json parser to parse the json data to DOM trees.

    Let's say now I now have two DOM trees - t1 and t2. Each tree will have many children nodes, which in turn will have many children nodes.

    What I'd like to do is traverse the tree t1 node by node and compare every node in t1 with every node in t2. I know Jackson json parser allows me to query specific nodes, but how do I traverse an entire tree node by node?

  • athreya86
    athreya86 about 12 years
    Yes. I could use JsonNode.iterator() to do that.. But I need the entire sub tree under the node(including any subtree under the child node) which is why I should use the recursive function that gbegley has suggested. Thanks!
  • athreya86
    athreya86 about 12 years
    my json doc is deeply nested. But, I'm going to try the function you have given above and make changes as I see fit. Do you have any suggestions/improvements that can be made(if the document is deeply nested)Thanks
  • gbegley
    gbegley about 12 years
    You should be okay unless your nesting depth is into the thousands. In that case, you might run into problems with the VM stack size, however, I suspect you would run into the same problems with the TreeMapper first. If you do, then you can use non-recursive implementation, but those are a bit more verbose. See [This] (stackoverflow.com/questions/1294701/…) to get started.
  • gbegley
    gbegley about 12 years
    Staxman may be right, see the JSONNode ObjectNode subclass source (equals implementation starts on line 533) to see if that might work for you.