无法读取 JSON:无法构造 `java.time.ZonedDateTime` 的实例(不存在像默认构造那样的创建者)

Could not read JSON: Cannot construct instance of `java.time.ZonedDateTime` (no Creators, like default construct, exist)

我有一个侦听队列然后将其映射到 POJO 的服务。 但是即使在设置了 ObjectMapper

@Configuration 之后我总是会收到这个错误
    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.registerModule(new JavaTimeModule());

        return mapper;
    }

我的 POJO:

public class ResultDto {
    private ZonedDateTime dateSent;

    private ZonedDateTime dateDeliveryReceiptReceived;

    public ResultDto() {}
}

我收到这个错误:

Caused by: org.springframework.messaging.converter.MessageConversionException: Could not read JSON: Cannot construct instance of `java.time.ZonedDateTime` (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2020-08-03T11:02:51.044+0000')

提前致谢!

使用 @JsonFormat(pattern = 'specify pattern here')

默认情况下,ObjectMapper 尝试在构造函数中使用 String 创建 ZonedDateTime 对象,但这样的事情不存在。通过添加此注释,您将允许它使用给定格式从 String 解析它。

从错误来看,它看起来像是在寻找 String-argument 构造函数。在 ResultDto 中添加以下构造函数后尝试:

public ResultDto(ZonedDateTime dateSent, ZonedDateTime dateDeliveryReceiptReceived) {
    this.dateSent = dateSent;
    this.dateDeliveryReceiptReceived = dateDeliveryReceiptReceived;
}

public ResultDto(String dateSent, String dateDeliveryReceiptReceived) {
    this.dateSent = ZonedDateTime.parse(dateSent, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"));
    this.dateDeliveryReceiptReceived = ZonedDateTime.parse(dateDeliveryReceiptReceived,
            DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"));
}

感谢那些回答的人。

在队友的帮助下,我们发现spring云有自己的对象映射器。而不是直接 ObjectMapper 。由于此 DTO/POJO 是来自 AWS SNS/SQS.

的消息

应该这样做:

@Bean
public MappingJackson2MessageConverter mappingJackson2MessageConverter(ObjectMapper objectMapper) {
    MappingJackson2MessageConverter jacksonMessageConverter = new MappingJackson2MessageConverter();
    jacksonMessageConverter.setObjectMapper(objectMapper);
    jacksonMessageConverter.setSerializedPayloadClass(String.class);
    jacksonMessageConverter.setStrictContentTypeMatch(true);
    return jacksonMessageConverter;
}