1. Overview

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

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

2. Ignore Null Fields on the Class

Jackson allows controlling this behavior at either the class level:

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

Or – more granularly – 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 configuring 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 shows 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 these examples and code snippets can be found in my Github project.