Skip to content
Advertisement

ObjectMapper writeValueAsString on ‘null’ vs ‘NullNode.getInstance()’

Consider the following statements:

String s1 = new ObjectMapper().writeValueAsString(null);

String s2 = new ObjectMapper().writeValueAsString(NullNode.getInstance());

In both the cases, serialized values s1 and s2 would be "null" (in String format). Jackson, by default, serializes null objects without any exception. What are the cases where we need to use NullNode, instead of directly serializing null?

Advertisement

Answer

"null" here is a string, not the null value. This is what writeValueAsString does: it wrote a null value or a NullNode as a "null" string.

The NullNode is a special type in Jackson that denotes the null value. For example, reading the following JSON will deserialize into a NullNode (which is a singleton):

JsonNode readValue = new ObjectMapper().readValue(" { "abc" : null }", JsonNode.class);
JsonNode jsonNode = readValue.get("abc"); // will return a NullNode
assertTrue(jsonNode == NullNode.getInstance());
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement