Customizing Jackson Null-Serialization in Spring Boot via BeanSerializerModifier
A common API-contract requirement is "no missing keys and no null values". Instead of sprinkling @JsonInclude on every DTO, we can teach Jackson to emit safe defaults globally. The following walk-through shows how to do it with a single BeanSerializerModifier, explains why two different Spring configuration styles work, and dives into the source to clarify why a third style silently fails.
- Declaring the Jackson customisation
@Configuration
public class JacksonConfig extends WebMvcConfigurationSupport {
@Override
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.stream()
.filter(MappingJackson2HttpMessageConverter.class::isInstance)
.map(MappingJackson2HttpMessageConverter.class::cast)
.forEach(c -> {
ObjectMapper om = c.getObjectMapper();
om.setSerializerFactory(
om.getSerializerFactory()
.withSerializerModifier(new NullToDefaultsModifier())
);
});
}
}
- The modifier and its null-replacements
public class NullToDefaultsModifier extends BeanSerializerModifier {
private static final JsonSerializer<Object> EMPTY_STRING = new EmptyStringSerializer();
private static final JsonSerializer<Object> EMPTY_ARRAY = new EmptyArraySerializer();
private static final JsonSerializer<Object> EMPTY_OBJECT = new EmptyObjectSerializer();
private static final JsonSerializer<Object> FALLBACK = new NullSerializer();
@Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config,
BeanDescription desc,
List<BeanPropertyWriter> props) {
props.forEach(w -> {
Class<?> raw = w.getType().getRawClass();
if (raw.isArray() || Collection.class.isAssignableFrom(raw)) {
w.assignNullSerializer(EMPTY_ARRAY);
} else if (Map.class.isAssignableFrom(raw) || !raw.getName().startsWith("java.lang")) {
w.assignNullSerializer(EMPTY_OBJECT);
} else if (raw == String.class) {
w.assignNullSerializer(EMPTY_STRING);
} else {
w.assignNullSerializer(FALLBACK);
}
});
return props;
}
/* ---------- concrete serializers ---------- */
private static final class EmptyStringSerializer extends JsonSerializer<Object> {
public void serialize(Object value, JsonGenerator gen, SerializerProvider p) throws IOException {
gen.writeString("");
}
}
private static final class EmptyArraySerializer extends JsonSerializer<Object> {
public void serialize(Object value, JsonGenerator gen, SerializerProvider p) throws IOException {
gen.writeStartArray();
gen.writeEndArray();
}
}
private static final class EmptyObjectSerializer extends JsonSerializer<Object> {
public void serialize(Object value, JsonGenerator gen, SerializerProvider p) throws IOException {
gen.writeStartObject();
gen.writeEndObject();
}
}
private static final class NullSerializer extends JsonSerializer<Object> {
public void serialize(Object value, JsonGenerator gen, SerializerProvider p) throws IOException {
gen.writeNull();
}
}
}
With the above in place, any null value is replaced by an appropriate empty literal:
{
"name": "", // null String
"tags": [], // null List
"meta": {}, // null POJO
"count": null // primitive wrapper, unchanged
}
- Alternative configuration without WebMvcConfigurationSupport
@Configuration
public class JacksonConfig {
@Bean
public MappingJackson2HttpMessageConverter jacksonConverter() {
MappingJackson2HttpMessageConverter c = new MappingJackson2HttpMessageConverter();
ObjectMapper om = c.getObjectMapper();
om.setSerializerFactory(
om.getSerializerFactory().withSerializerModifier(new NullToDefaultsModifier())
);
return c;
}
}
This works unless another configuration class already extends WebMvcConfigurationSupport. Understanding why requires a short trip into Spring Boot internals.
- Why extendMessageConverters is necessary
When @SpringBootApplication is processed, @EnableAutoConfiguration imports WebMvcAutoConfiguration. That configuration is guarded by
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
As soon as any user class extends WebMvcConfigurationSupport, the auto-configuration backs off and the user class becomes responsible for MVC setup. Inside WebMvcConfigurationSupport the RequestMappingHandlerAdapter is created like this:
@Bean
public RequestMappingHandlerAdapter requestMappingHandlerAdapter(...) {
RequestMappingHandlerAdapter adapter = createRequestMappingHandlerAdapter();
adapter.setMessageConverters(getMessageConverters()); // <-- important
...
}
getMessageConverters() populates a list by calling:
configureMessageConverters(List)– meant for plementing the listaddDefaultHttpMessageConverters(List)– adds Boot’s defaultsextendMessageConverters(List)– post-process hook
Only extendMessageConverters is guaranteed to run after the default MappingJackson2HttpMessageConverter has been added, which is why overriding it is the safest place to tweak the ObjectMapper.
- Why a @Bean MappingJackson2HttpMessageConverter is ignored
If WebMvcConfigurationSupport is in play, the adapter’s converters are taken from the getMessageConverters() list, not from the application context. Thereofre a standalone @Bean declared eleswhere is never injected into the adapter and has no effect.
Conversely, when no WebMvcConfigurationSupport subclass exists, WebMvcAutoConfiguration.EnableWebMvcConfiguration delegates to DelegatingWebMvcConfiguration. That class collects all WebMvcConfigurer beans (including the one implicitly created by declaring a MappingJackson2HttpMessageConverter @Bean) and adds them via configureMessageConverters. Hence the custom converter is picked up and registered.
- Where the modifier is actually applied
Regardless of how the converter is registered, Jackson ultimately serialises fields through BeanPropertyWriter.serializeAsField. Inside that method:
if (value == null) {
if (_nullSerializer != null) {
gen.writeFieldName(_name);
_nullSerializer.serialize(null, gen, provider);
}
return;
}
Our NullToDefaultsModifier runs during serializer construction (BeanSerializerFactory.constructBeanOrAddOnSerializer) and installs the desired _nullSerializer for each property, producing the empty literals shown earlier.
With these pieces in place, the API always returns well-formed JSON without ever exposing null.