Search code examples
javaserializationobjectmapper

Why does ObjectMapper serialization with JsonInclude.NON_EMPTY also remove null fields?


JsonInclude.NON_EMPTY and JsonInclude.NON_NULL are two Jackson annotations that can be used to control which fields are included in the serialized JSON output.

- JsonInclude.NON_EMPTY will ignore fields whose values are empty, such as empty strings, empty collections.
- JsonInclude.NON_NULL will only ignore fields whose values are null.

If I register JsonInclude.NON_EMPTY with the ObjectMapper, then not only fields with empty but also null values will be ignored when serializing objects. Why would NON_EMPTY ignore null fields?

Below is the code

@Builder
class Person {
   String firstName;
   String middleName;
   String lastName;
}

@Test
void testSerialization() {
   Person person = Person()
                   .builder()
                   .firstName("test")
                   .middleName("")
                   .lastName(null)
                   .build();

   ObjectMapper mapper1 = new ObjectMapper();
   mapper1.setSerializationInclusion(Include.NON_EMPTY);
   String deserializeStr1 = mapper1.writeValueAsString(person);
   // deserializeStr1: { "firstName": "test" }
   // why does "lastName" not present? 
   // why not being: { "firstName": "test", "lastName": null } ?
}

Solution

  • Please check out the javadoc for JsonInclude.NON_EMPTY it says:

    "Value that indicates that only properties with null value, or what is considered empty, are not to be included".

    Also:

    "Default emptiness for all types includes:

    Null values."

    so i would say that NON_EMPTY is a superset of NON_NULL, so thats why the lastname which is null is not present. Also, when I was testing, I was unable to serialize your Person class. I had to add the @Value annotation from lombok before my spring application could serialize it properly