问题描述
我有一个来自第三方库的类型(来自jooq的JSONB
),我为以下代码编写了一个自定义序列化器/反序列化器:
@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字段吗?
解决方法
您需要创建新的 "definitions": {
"short_string": {
"type": "string","maxLength": 20
},...
},"properties": {
"name": { "$ref": "#/definitions/short_string" },...
}
实例并注册所有自定义序列化器和反序列化器。接下来,您需要检查如何在您的com.fasterxml.jackson.databind.module.SimpleModule
版本中注册新的自定义模块。
Spring Boot
看看:
- 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