Last active
October 13, 2023 23:35
-
-
Save tedpennings/6253541 to your computer and use it in GitHub Desktop.
A very simple search implementation for Jackson JsonNodes using recursive DFS
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
private JsonNode searchForEntity(JsonNode node, String entityName) { | |
// A naive depth-first search implementation using recursion. Useful | |
// **only** for small object graphs. This will be inefficient | |
// (stack overflow) for finding deeply-nested needles or needles | |
// toward the end of a forest with deeply-nested branches. | |
if (node == null) { | |
return null; | |
} | |
if (node.has(entityName)) { | |
return node.get(entityName); | |
} | |
if (!node.isContainerNode()) { | |
return null; | |
} | |
for (JsonNode child : node) { | |
if (child.isContainerNode()) { | |
JsonNode childResult = searchForEntity(child, entityName); | |
if (childResult != null && !childResult.isMissingNode()) { | |
return childResult; | |
} | |
} | |
} | |
// not found fall through | |
return null; | |
} | |
// Usage: | |
// Given the following JSON: {"d":{"EntitySets":["BusinessTripView","Person","BusinessTrip"]}} | |
// searchForEntity(rootJsonNode, "EntitySets"); # returns the container node for the search key, in this case ["BusinessTripView","Person","BusinessTrip"] |
If you have the full path of the entity you want to search for, you can do a breadth first search instead, right?
E.g. if you have {"a": {"b": "some text"}, "c": {"d": "some other text"}}, and we want to get a.c.d
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍