我有一个来自第三方库的类型(JSONB
来自 jooq),我为它编写了一个自定义序列化器/反序列化器:
@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)
注释项目中的每个 JSONB 字段和 @JsonDeserialize(using = JSONBDeserializer.class)
?
最佳答案
您需要创建新的 com.fasterxml.jackson.databind.module.SimpleModule
实例并注册所有自定义序列化器和反序列化器。接下来,您需要检查如何在您的 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
关于java - 是否可以在 spring 中默认为类型使用自定义序列化器/反序列化器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64505346/