gpt4 book ai didi

Java Jackson反序列化实现接口(interface)的抽象类子类

转载 作者:行者123 更新时间:2023-12-05 07:00:26 35 4
gpt4 key购买 nike

我有一个界面:

@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = ChildA.class, name = "childA"),
@JsonSubTypes.Type(value = ChildB.class, name = "childB"),
})
public interface Event {
}

然后是实现这个接口(interface)的抽象类:

public abstract class SpecificEvent implements Event {
private ZonedDateTime timestamp;
}

最后是抽象类的 child :

public class ChildA extends SpecificEvent {
}

public class ChildB extends SpecificEvent {
}

Jackson 无法反序列化子项并出现错误:

Could not resolve type id 'childA' as a subtype ofpackages.SpecificEvent.

我做错了什么?

UPD

我正在消费 children throw RabbitMQ 的消息。兔子配置:

   public ObjectMapper objectMapper() {
var mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.registerModule(new Jdk8Module());
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
mapper.setDateFormat(StdDateFormat.instance
.withTimeZone(TimeZone.getTimeZone(ZoneId.of("Europe/Moscow")))
.withLocale(new Locale("ru"))
);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper;
}

public MessageConverter jsonMessageConverter() {
return new Jackson2JsonMessageConverter(objectMapper());
}

我只使用 RabbitTemplate 来发送事件:

    rabbitTemplate.convertAndSend(
exchange.getName(),
event.getEventRouteKey().getKey(),
event
);

并通过@RabbitListener 收听。

最佳答案

实际上,我忘记在更改模型之前清除 Rabbit 中的队列,这就是我出现反序列化错误的原因。

关于Java Jackson反序列化实现接口(interface)的抽象类子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64123084/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com