[英]Java Jackson deserialize abstract class child which implements interface
我有一個界面:
@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 {
}
然后是實現這個接口的抽象類:
public abstract class SpecificEvent implements Event {
private ZonedDateTime timestamp;
}
最后是抽象類的孩子:
public class ChildA extends SpecificEvent {
}
public class ChildB extends SpecificEvent {
}
傑克遜未能反序列化兒童錯誤:
無法將類型 ID 'childA' 解析為
packages.SpecificEvent
的子類型。
我究竟做錯了什么?
UPD
我正在消費孩子們拋出 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 中清除隊列,這就是我遇到反序列化錯誤的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.