【发布时间】:2021-04-02 03:23:05
【问题描述】:
我需要为我的一个实体“付款”编写一个自定义序列化程序,我必须通过扩展 StdSerializer 来实现它:
class Payment {
}
class PaymentSerializer extends StdSerializer<Payment> {
public PaymentSerializer() {
this(null);
}
public PaymentSerializer(Class<Payment> t) {
super(t);
}
@Override
public void serialize(Payment value, JsonGenerator gen, SerializerProvider provider) throws IOException {
// some logics
}
}
由于我使用的是 Spring,所以我注册了这个 Serializer,以便 Spring 可以识别它:
@Bean
public Jackson2ObjectMapperBuilder serializersObjectMapperBuilder() {
SimpleModule module = new SimpleModule();
module.addSerializer(Payment.class, applicationContext.getBean(PaymentSerializer.class));
return new Jackson2ObjectMapperBuilder().modules(module);
}
现在我有一个控制器可以将数据返回给客户端,它使用这个序列化器没有任何问题:
@RestController
@RequestMapping("/payment")
class PaymentController {
@GetMapping
public List<Payment> getAll() {
return Arrays.asList(new Payment());
}
}
从现在开始,我的序列化器工作正常,一切都很好。
问题出在另一个实体“订单”上,该实体将支付作为@JsonUnwrapped 的属性:
class Order {
@JsonUnwrapped
private Payment payment;
}
我需要解开Order 中的Payment,并且我想使用相同的PaymentSerializer,但问题是当我使用这个自定义序列化器时,@JsonUnwrapped 注释将被忽略输出将是这样的:
{
"payment": {
.....
}
}
正如我所提到的,我想消除“付款”字段并打开它。
我知道要为自定义序列化器模拟@JsonUnwrapped,我需要扩展UnwrappingBeanSerializer 类,但正如我一开始提到的,我也需要标准序列化器。
更改我的实体模型不是我的选择。
有没有办法做到这一点?
我使用Spring Boot 2.1.3.RELEASE,我相信它使用Jackson 2.9
【问题讨论】:
标签: spring-boot jackson jackson2 jackson-modules