在春季,默认情况下是否可以对类型使用自定义序列化器/反序列化器? [英] Is it possible to use a custom serializer/deserializer for a type by default in spring?

查看:59
本文介绍了在春季,默认情况下是否可以对类型使用自定义序列化器/反序列化器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自第三方库的类型(JSONB来自 jooq ),我已经为以下内容编写了自定义序列化器/反序列化器:

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

我想知道是否有一种方法可以告诉spring或jackson默认使用它们,而不必用@JsonSerialize(using = JSONBSerializer.class)@JsonDeserialize(using = JSONBDeserializer.class)注释项目中的每个JSONB字段吗?

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)?

推荐答案

您需要创建新的com.fasterxml.jackson.databind.module.SimpleModule实例并注册所有自定义序列化程序和反序列化程序.接下来,您需要查看如何在您的Spring Boot版本中注册新的自定义模块.

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

看看:

  • 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

这篇关于在春季,默认情况下是否可以对类型使用自定义序列化器/反序列化器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆