0

I've a springboot application. I'm trying to replace null values with a custom string ("NA"). So, I've configured an object mapper with a custom serializer provider that in turn has a custom null value serializer. You can check the code below.

@Configuration
public class JacksonConfig {
    @Bean
    public ObjectMapper jacksonObjectMapper() {
        return new CustomObjectMapper();
    }

    @Bean
    public SerializationConfig serializationConfig() {
        return jacksonObjectMapper().getSerializationConfig();
    }
}

class CustomObjectMapper extends ObjectMapper {
    CustomObjectMapper() {
        super();
        DefaultSerializerProvider.Impl serializerProvider = new DefaultSerializerProvider.Impl();
        serializerProvider.setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
                gen.writeString("NA");
            }
        });
        this.setSerializerProvider(serializerProvider);
    }
}

Now the problem is, even these beans are getting created, the custom null value serializer is still not taking effect. In the response, I'm still seeing lot of null values. Is there anything else I'm missing here?

pkgajulapalli
  • 1,066
  • 3
  • 20
  • 44
  • 1
    Try to override `MappingJackson2HttpMessageConverter` as well. See my answer to this question: [How to enable 'ALLOW_NUMERIC_LEADING_ZEROS' feature to allow leading zeroes in JSON Request Body?](https://stackoverflow.com/questions/55795970/how-to-enable-allow-numeric-leading-zeros-feature-to-allow-leading-zeroes-in-j/55820403#55820403). See also: [How to configure MappingJacksonHttpMessageConverter while using spring annotation-based configuration?](https://stackoverflow.com/questions/10650196/how-to-configure-mappingjacksonhttpmessageconverter-while-using-spring-annotatio#10650452) – Michał Ziober Aug 07 '19 at 09:56
  • @MichałZiober, thanks for your input. It is working. Is there anyway to use it for serializing certain classes only? – pkgajulapalli Aug 07 '19 at 11:48
  • Do you want to use your custom `NullValueSerializer` for certain classes? For other classes you want to see default `null` value instead? – Michał Ziober Aug 07 '19 at 23:31
  • Yes, I want to use it for selected classes only. Not all of them. – pkgajulapalli Aug 08 '19 at 03:35

0 Answers0