For your scenario with a dynamic JSON structure in a Spring Boot application, I recommend using Jackson's JsonNode approach. Here's a robust solution:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonExtractor {
private static final ObjectMapper objectMapper = new ObjectMapper();
public String extractValueFromPaths(String jsonString, List<String> possiblePaths) {
try {
JsonNode rootNode = objectMapper.readTree(jsonString);
for (String path : possiblePaths) {
String extractedValue = extractValueFromPath(rootNode, path);
if (extractedValue != null) {
return extractedValue;
}
}
return null; // No matching path found
} catch (Exception e) {
// Handle parsing exceptions
throw new RuntimeException("Error parsing JSON", e);
}
}
private String extractValueFromPath(JsonNode rootNode, String path) {
String[] pathSegments = path.split("\\.");
JsonNode currentNode = rootNode;
for (String segment : pathSegments) {
if (currentNode == null) return null;
currentNode = currentNode.path(segment);
// Check if the node is missing or null
if (currentNode.isMissingNode() || currentNode.isNull()) {
return null;
}
}
// Convert the final node to a string
return currentNode.asText();
}
// Example usage
public void demonstrateUsage() {
String jsonString = "{\"user\":{\"profile\":{\"name\":\"John\"}}, \"alternate\":{\"info\":\"Data\"}}";
List<String> paths = Arrays.asList(
"user.profile.name",
"alternate.info",
"non.existent.path"
);
String result = extractValueFromPaths(jsonString, paths);
System.out.println(result); // Would print "John" or "Data"
}
}
Why this approach is recommended:
- Flexibility: JsonNode allows you to navigate through dynamic JSON structures easily.
- Null Safety: The
path() method returns a MissingNode instead of throwing an exception if a path doesn't exist.
- Performance: Jackson is highly optimized for JSON parsing.
- Nested Path Handling: The method can handle paths up to 5 levels deep.
Key benefits:
- Handles missing paths gracefully
- Tries multiple path combinations
- Works with deeply nested and dynamic JSON structures
- Converts final node to a string (you can modify to return other types if needed)
Potential improvements:
- Add type-specific extraction methods
- Implement more sophisticated error handling
- Add logging for path resolution attempts
Compared to your initial ideas:
- Better than parsing to specific Java objects (too rigid)
- More robust than using
Map<String, Node>
- Provides clean, type-safe navigation
Recommendations:
- Ensure you have the Jackson dependency in your
pom.xml:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
This approach gives you the flexibility to handle dynamic JSON structures while providing a clean, type-safe method to extract values from various potential paths.