Reputation: 98
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?
Upvotes: 4
Views: 15415
Reputation: 1356
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.
Upvotes: 1
Reputation: 13139
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.
Upvotes: 4
Reputation: 2679
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.
Upvotes: 1