Jackson: is it possible to replace the set of serializers with @JsonSerialize annotation (like ObjectMapper)?

Quick question: is it possible to override attribute @JsonSerialize

( using

) with ObjectMapper?

I have it built spring-security-oauth2

in and I want to customize OAuth2Exception

the JSON serialization way . The problem is that this class uses

@JsonSerialize(using = OAuth2ExceptionJackson2Serializer.class)

      

I tried to register my own serializer with:

SimpleModule module = new SimpleModule()
module.addSerializer(OAuth2Exception, new JsonSerializer<OAuth2Exception>() {
    @Override
    void serialize(OAuth2Exception value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        jgen.writeString('{"test":"test"}')
    }
})

ObjectMapper objectMapper = new ObjectMapper()
objectMapper.registerModule(module)

      

but that didn't work - the c serializer is @JsonSerialize

used instead of the custom one.

Is there any other way to replace the serializer set with @JsonSerialize

?

PS: the example code is written in groovy

+3


source to share


1 answer


In such a case, Jackson has a mechanism called mixing annotations .

You can create a class that overrides the initial annotations.

@JsonSerialize(using=MySerializer.class)
public static abstract class OAuth2ExceptionMixIn {

}

      



Then register it in the mapper object:

objectMapper.addMixIn(OAuth2Exception.class, OAuth2ExceptionMixIn.class);

      

What is it. Jackson should now use yours MySerializer

instead of the initial one OAuth2ExceptionJackson2Serializer

.

+3


source







All Articles