Why should we use jsonNode.hasNonNull("key") instead of jsonNode.get("key") == null in a JsonNode?
Using jsonNode.hasNonNull("key") instead of jsonNode.get("key") == null is a better practice for several reasons:
1. Handles Missing Keys More Clearly
{
"name": null
}
However, if the key itself is missing:
{}
2. Avoids Unexpected NullPointerException
Example:
if (jsonNode.get("key") != null && jsonNode.get("key").asText().equals("value")) {
// May throw NullPointerException if "key" is explicitly set to null in JSON
}
Instead, using:
if (jsonNode.hasNonNull("key") && jsonNode.get("key").asText().equals("value")) {
// Safe, since we already checked the value is not null
}
3. Better Readability and Intent
Conclusion
Prefer jsonNode.hasNonNull("key") when you need to check if a key exists and its value is not null, making your code safer and more readable.
Avoiding unexpected NullPointerException part is really helpful. I suppose if jsonNode.get("key") is not null, and contains valid JsonNode as a value then we have to stick with .get(), .has() etc. suggestions ???