繁体   English   中英

Java Jackson 反序列化实现接口的抽象类孩子

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM