Skip to content

Instantly share code, notes, and snippets.

@tedpennings
Last active October 13, 2023 23:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tedpennings/6253541 to your computer and use it in GitHub Desktop.
Save tedpennings/6253541 to your computer and use it in GitHub Desktop.
A very simple search implementation for Jackson JsonNodes using recursive DFS
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"]
@andermirik
Copy link

👍

@mabbay
Copy link

mabbay commented Jan 31, 2023

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