简体   繁体   中英

Jackson json : traversing a json tree node by node

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?

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 .

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.

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM