Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Customizing Jackson Null-Serialization in Spring Boot via BeanSerializerModifier

Tech Nov 23 1

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.

  1. 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())
                      );
                  });
    }
}

  1. 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
}

  1. 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.

  1. 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:

  1. configureMessageConverters(List) – meant for plementing the list
  2. addDefaultHttpMessageConverters(List) – adds Boot’s defaults
  3. extendMessageConverters(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.

  1. 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.

  1. 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.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.