Is it possible to use a custom serializer/deserializer for a type by default in spring?

好久不见. 提交于 2021-02-08 05:25:32

问题


I have a type from a third party library (JSONB from jooq) that I've written a custom serializer/deserializer for:

@JsonComponent
public class JSONBSerializer extends JsonSerializer<JSONB> {
    @Override
    public void serialize(JSONB jsonb, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString(jsonb.toString());
    }
}
@JsonComponent
public class JSONBDeserializer extends JsonDeserializer<JSONB> {
    @Override
    public JSONB deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        return JSONB.valueOf(jsonParser.getValueAsString());
    }
}

I am wondering if there is a way to tell spring or jackson to use these by default without having to annotate every JSONB field in the project with @JsonSerialize(using = JSONBSerializer.class) and @JsonDeserialize(using = JSONBDeserializer.class)?


回答1:


You need to create new com.fasterxml.jackson.databind.module.SimpleModule instance and register all custom serialisers and deserialisers. Next, you need to check out how to register new custom module in your version of Spring Boot.

@Bean
public SimpleModule jooqModule() {
    SimpleModule jooqModule = new SimpleModule();
    jooqModule.addSerializer(JSONB.class, new JSONBSerializer());
    jooqModule.addDeserializer(JSONB.class, new JSONBDeserializer());
}

Take a look at:

  • How can I register and use the jackson AfterburnerModule in Spring Boot?
  • Jackson global settings to deserialise array to custom list implementation
  • Jackson custom serialization and deserialization
  • In Spring Boot, adding a custom converter by extending MappingJackson2HttpMessageConverter seems to overwrite the existing converter
  • Customizing HttpMessageConverters with Spring Boot and Spring MVC


来源:https://stackoverflow.com/questions/64505346/is-it-possible-to-use-a-custom-serializer-deserializer-for-a-type-by-default-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!