在春季,默认情况下是否可以对类型使用自定义序列化器/反序列化器? [英] Is it possible to use a custom serializer/deserializer for a type by default in spring?
问题描述
我有一个来自第三方库的类型(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());
}
看看:
- 如何注册和在Spring Boot中使用jackson AfterburnerModule吗?
- 将杰克逊全局设置反序列化为自定义列表的杰克逊全局设置实施
- Jackson自定义序列化和反序列化
- 在Spring Boot中,通过添加一个自定义转换器扩展MappingJackson2HttpMessageConverter似乎会覆盖现有的转换器
- 使用Spring Boot和Spring MVC自定义HttpMessageConverters
- 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屋!