
Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:
Once the early-adopter seats are all used, the price will go up and stay at $33/year.
Last updated: February 9, 2023
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.
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")));
}
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")));
}
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.