Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I register my JsonSerializer on Spring

Taking the response from this question: https://stackoverflow.com/a/45566139/2968729 I want to add the NullSerializer to the autoconfigured ObjectMapper. Spring Boot documentation:

Any beans of type com.fasterxml.jackson.databind.Module are automatically registered with the auto-configured Jackson2ObjectMapperBuilder and are applied to any ObjectMapper instances that it creates. This provides a global mechanism for contributing custom modules when you add new features to your application.

So this is how I'm trying:

@Configuration
public class JacksonConfig {

    @Bean
    public Module customSerializer() {
        SimpleModule module = new SimpleModule();
        module.addSerializer(new NullSerializer());
        return module;
    }
}

But I'm getting:

NullSerializer does not define valid handledType() -- must either register with method that takes type argument or make serializer extend com.fasterxml.jackson.databind.ser.std.StdSerializer

Javadoc of handleType() method says:

Method for accessing type of Objects this serializer can handle. Note that this information is not guaranteed to be exact -- it may be a more generic (super-type) -- but it should not be incorrect (return a non-related type). Default implementation will return null, which essentially means same as returning Object.class would; that is, that nothing is known about handled type.

Using Spring Boot 2.0.5.RELEASE

like image 654
anat0lius Avatar asked Sep 15 '25 22:09

anat0lius


1 Answers

I think the problem is that you're using the raw type. You need to give it a class.

module.addSerializer(Object.class, new NullSerializer<>());
like image 99
Michael Avatar answered Sep 18 '25 11:09

Michael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!