Created
June 6, 2016 22:45
-
-
Save benjaminaaron/381c6e40e8b0843cc5c23ec093f3432f to your computer and use it in GitHub Desktop.
WIP validating parsedTree against constructedTree (Jackson)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.fasterxml.jackson.databind.JsonNode; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
import com.fasterxml.jackson.databind.node.ObjectNode; | |
import java.io.IOException; | |
import java.util.Iterator; | |
public class Main { | |
public static void main(String[] args) throws IOException { | |
ObjectMapper mapper = new ObjectMapper(); | |
String json = "{" + | |
"\"nodeA\": 1, " + | |
"\"nodeB\": {" + | |
"\"nodeBchild1\": \"foo\", " + | |
"\"nodeBchild2\": {" + | |
"\"nodeBchild2child1\": true" + | |
"}}}"; | |
JsonNode parsedRoot = mapper.readTree(json); | |
System.out.println(parsedRoot.toString()); | |
JsonNode constructedRoot = mapper.createObjectNode(); | |
((ObjectNode) constructedRoot).put("nodeA", 1); | |
JsonNode nodeB = mapper.createObjectNode(); | |
((ObjectNode) constructedRoot).set("nodeB", nodeB); | |
((ObjectNode) nodeB).put("nodeBchild1", "foo"); | |
JsonNode nodeBchild2 = mapper.createObjectNode(); | |
((ObjectNode) nodeB).set("nodeBchild2", nodeBchild2); | |
((ObjectNode) nodeBchild2).put("nodeBchild2child1", true); | |
System.out.println(constructedRoot.toString()); | |
// traverse through parsedRoot and compare every entry to constructedRoot | |
JsonNode node = constructedRoot.findPath("nodeBchild2child1"); | |
if (node.isMissingNode()) { | |
// constructedRoot doesn't have this node | |
} else { | |
recursive(constructedRoot); | |
} | |
} | |
public static void recursive(JsonNode node) { | |
System.out.println("at node " + node); | |
Iterator<JsonNode> it = node.elements(); | |
while (it.hasNext()) { | |
JsonNode child = it.next(); | |
recursive(child); | |
} | |
} | |
} | |
// www.tutorialspoint.com/jackson/jackson_tree_model.htm | |
// http://wiki.fasterxml.com/JacksonInFiveMinutes | |
// www.mkyong.com/java/jackson-tree-model-example/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment