You're working with a dynamic and deeply nested JSON structure, where the exact schema may vary, and you need to extract values from multiple possible paths (some of which may not exist). You're also using Java 21 and Spring Boot, which gives you access to modern features and libraries.
✅ Summary of Your Requirements:
- Extract data from nested JSON fields up to 5 levels deep
- Use a list of possible paths, trying each until one works
- The JSON is very dynamic, so strict POJO mapping is not ideal
🚀 Recommended Approach: Use JsonNode + Jackson
This is a perfect use case for Jackson's JsonNode API. It allows you to:
- Parse the JSON into a tree structure (
JsonNode)
- Traverse it dynamically
- Safely check for existence of nested paths without throwing exceptions
- Handle missing nodes gracefully
This is much more flexible than trying to map the whole JSON to Java objects (which would require writing many DTOs or using generic Maps, both of which can get messy quickly).
🔍 Why Not Map<String, Object>?
While you can parse JSON into a Map<String, Object> (or nested maps), this becomes very cumbersome when dealing with deeper nesting (e.g., "a.b.c.d.e"). You'd have to manually cast and check every level:
Map<String, Object> map = objectMapper.readValue(json, new TypeReference<>() {});
Object value = ((Map) ((Map) ((Map) ((Map) map.get("a")).get("b")).get("c")).get("d")).get("e");
That’s error-prone and hard to maintain.
💡 Best Practice: Use JsonNode + at() or findValue()
Example:
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(jsonString);
Now, for a list of candidate paths like:
List<String> candidatePaths = List.of("/a/b/c", "/x/y/z", "/p/q/r");
You can try them in order:
Optional<JsonNode> foundNode = candidatePaths.stream()
.map(path -> {
try {
return rootNode.at(path);
} catch (JsonProcessingException e) {
return null; // invalid path or format
}
})
.filter(node -> node != null && !node.isMissing())
.findFirst();
foundNode.ifPresent(node -> {
System.out.println("Found value: " + node.asText());
});
Notes:
JsonNode.at(String jsonPointer) accepts JSON Pointer syntax like /a/b/c
isMissing() checks if the node doesn't exist
- No exceptions are thrown for missing nodes — very safe to use
- Very concise and readable code
🧠 Tips for Working with Dynamic JSON
- Use Jackson’s
readTree() to parse JSON strings into JsonNode
- Precompute all possible paths as a list, ordered by priority
- Gracefully handle missing nodes
- Convert values using
.asText(), .asInt(), etc.
- Avoid casting raw values unless necessary
🛠 Bonus: Custom Utility Method
Here's a helper method to make your life easier:
public Optional<JsonNode> findFirstExistingPath(JsonNode root, List<String> paths) {
return paths.stream()
.map(path -> {
try {
return root.at(path);
} catch (JsonProcessingException e) {
return null;
}
})
.filter(node -> node != null && !node.isMissing())
.findFirst();
}
Usage:
JsonNode result = findFirstExistingPath(rootNode, List.of("/a/b/c", "/x/y/z"))
.orElseThrow(() -> new RuntimeException("No valid path found"));
✅ Conclusion
Given your requirements:
- JSON is dynamic
- Paths are nested and optional
- Need to try several paths until one matches
👉 The best approach is to use Jackson's JsonNode and at() with JSON Pointer paths.
It gives you:
- Flexibility
- Safety (no NPEs on missing nodes)
- Readable and maintainable code
Let me know if you want an example using Jayway JsonPath as an alternative!