You can configure property inclusion, and numerous other settings, via application.properties
:
spring.jackson.default-property-inclusion=non_null
There's a table in the documentation that lists all of the properties that can be used.
If you want more control, you can also customize Spring Boot's configuration programatically using a Jackson2ObjectMapperBuilderCustomizer
bean, as described in the documentation:
The context’s
Jackson2ObjectMapperBuilder
can be customized by one or moreJackson2ObjectMapperBuilderCustomizer
beans. Such customizer beans can be ordered (Boot’s own customizer has an order of 0), letting additional customization be applied both before and after Boot’s customization.
Lastly, if you don't want any of Boot's configuration and want to take complete control over how the ObjectMapper
is configured, declare your own Jackson2ObjectMapperBuilder
bean:
@Bean
Jackson2ObjectMapperBuilder objectMapperBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
// Configure the builder to suit your needs
return builder;
}