Course – LS (cat=JSON/Jackson)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

This quick tutorial is going to cover how to set up Jackson to ignore null fields when serializing a java class.

If we want to dig deeper and learn other cool things to do with the Jackson 2, we can head on over to the main Jackson tutorial.

Further reading:

Jackson - Change Name of Field

Jackson - Change the name of a field to adhere to a specific JSON format.

Jackson - Decide What Fields Get Serialized/Deserialized

How to control which fields get serialized/deserialized by Jackson and which fields get ignored.

2. Ignore Null Fields on the Class

Jackson allow us to control this behavior at either the class level:

@JsonInclude(Include.NON_NULL)
public class MyDto { ... }

Or with more granularity at the field level:

public class MyDto {

    @JsonInclude(Include.NON_NULL)
    private String stringValue;

    private int intValue;

    // standard getters and setters
}

Now we should be able to test that null values are indeed not part of the final JSON output:

@Test
public void givenNullsIgnoredOnClass_whenWritingObjectWithNullField_thenIgnored()
  throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    MyDto dtoObject = new MyDto();

    String dtoAsString = mapper.writeValueAsString(dtoObject);

    assertThat(dtoAsString, containsString("intValue"));
    assertThat(dtoAsString, not(containsString("stringValue")));
}

3. Ignore Null Fields Globally

Jackson also allows us to configure this behavior globally on the ObjectMapper:

mapper.setSerializationInclusion(Include.NON_NULL);

Now any null field in any class serialized through this mapper is going to be ignored:

@Test
public void givenNullsIgnoredGlobally_whenWritingObjectWithNullField_thenIgnored() 
  throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_NULL);
    MyDto dtoObject = new MyDto();

    String dtoAsString = mapper.writeValueAsString(dtoObject);

    assertThat(dtoAsString, containsString("intValue"));
    assertThat(dtoAsString, containsString("booleanValue"));
    assertThat(dtoAsString, not(containsString("stringValue")));
}

4. Conclusion

Ignoring null fields is such a common Jackson configuration because it’s often the case that we need to have better control over the JSON output. This article demonstrates how to do that for classes. There are, however, more advanced use cases, such as ignoring null values when serializing a Map.

The implementation of all of these examples and code snippets can be found in the Github project.

Course – LS (cat=JSON/Jackson)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – Jackson (eBook) (cat=Jackson)
Comments are closed on this article!