是否可以在 spring 中默认为类型使用自定义 serializer/deserializer?
Is it possible to use a custom serializer/deserializer for a type by default in spring?
我有一个来自第三方库的类型(JSONB
来自 jooq),我已经为 serializer/deserializer 编写了一个自定义类型:
@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 字段?
您需要创建新的 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?
- Customizing HttpMessageConverters with Spring Boot and Spring MVC
我有一个来自第三方库的类型(JSONB
来自 jooq),我已经为 serializer/deserializer 编写了一个自定义类型:
@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 字段?
您需要创建新的 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?
- Customizing HttpMessageConverters with Spring Boot and Spring MVC