Java Jackson 反序列化抽象 class child 实现接口
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 {
}
然后实现这个接口的抽象class:
public abstract class SpecificEvent implements Event {
private ZonedDateTime timestamp;
}
最后 children 摘要 class:
public class ChildA extends SpecificEvent {
}
public class ChildB extends SpecificEvent {
}
Jackson 反序列化 children 失败,出现错误:
Could not resolve type id 'childA' as a subtype of
packages.SpecificEvent
.
我做错了什么?
UPD
我正在使用 children 抛出 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 中的队列,这就是我出现反序列化错误的原因。
我有一个接口:
@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 {
}
然后实现这个接口的抽象class:
public abstract class SpecificEvent implements Event {
private ZonedDateTime timestamp;
}
最后 children 摘要 class:
public class ChildA extends SpecificEvent {
}
public class ChildB extends SpecificEvent {
}
Jackson 反序列化 children 失败,出现错误:
Could not resolve type id 'childA' as a subtype of
packages.SpecificEvent
.
我做错了什么?
UPD
我正在使用 children 抛出 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 中的队列,这就是我出现反序列化错误的原因。