Why should we use jsonNode.hasNonNull("key") instead of jsonNode.get("key") == null in a JsonNode?

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

  • jsonNode.get("key") == null: This checks if the key itself is missing.
  • jsonNode.hasNonNull("key"): This checks if the key exists and its value is not null

{
    "name": null
}        

  • jsonNode.get("name") == null → False (key exists, but value is null)
  • jsonNode.hasNonNull("name") → False (because value is null)

However, if the key itself is missing:

{}        

  • jsonNode.get("name") == null → True
  • jsonNode.hasNonNull("name") → False

2. Avoids Unexpected NullPointerException

  • If jsonNode.get("key") is not null, but contains null as a value, calling .asText(), .asInt(), etc., may cause exceptions.
  • hasNonNull("key") ensures the value is not null before further operations.

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

  • hasNonNull("key") clearly expresses that we care about both existence and non-null values.
  • get("key") == null may be misinterpreted as checking only for existence.

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 ???

Like
Reply

To view or add a comment, sign in

More articles by Naveen Gupta

Explore content categories