本文介绍了Java Spring:Jackson 反序列化到 ZonedDateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想使用以下类从外部 JSON 负载进行反序列化:

Assuming the following class I want to use for deserialization from an external JSON payload:

public class MyObject {

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    private ZonedDateTime timestamp;

}

当我尝试使用 JSON 负载时,Jackson 抛出以下错误:

When I'm trying to consume the JSON payload, Jackson throws the following error:

Cannot deserialize value of type `java.time.ZonedDateTime` from String "2019-01-23T12:54:18.610Z": Failed to deserialize java.time.ZonedDateTime: (java.time.format.DateTimeParseException) Text '2019-01-23T12:54:18.610Z' could not be parsed at index 23

如您所见,传入的字符串是 "2019-01-23T12:54:18.610Z",据我所知,这是一个有效的 ZonedDateTime.使用 jshell,使用 ZonedDateTime.parse("2019-01-23T12:54:18.610Z") 将该字符串解析为 ZonedDateTime 会产生我所期望的有效 ZonedDateTime.

As you can see, the incoming string is "2019-01-23T12:54:18.610Z", which is a valid ZonedDateTime as I understand it. Using jshell, parsing that string into a ZonedDateTime using ZonedDateTime.parse("2019-01-23T12:54:18.610Z") results in a valid ZonedDateTime as I would expect.

  • 为什么杰克逊在这里失败了?
  • 我该怎么做才能让它发挥作用?

我也不是 Spring 或 Jackson 的专家.谢谢.

I'm not an expert on Spring or Jackson, either. Thanks.

我使用的是 Spring Boot v2.1.1.RELEASE.

I'm using Spring Boot v2.1.1.RELEASE.

推荐答案

模式中的 Z 不接受值中的字面值 'Z',改用 X 应该可行:

The Z in the pattern won't accept a literal 'Z' in the value, using X instead should work:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX")

模式被指定为 Java SimpleDateFormat - Java 10 参考 此处.

The pattern is specified as a Java SimpleDateFormat - Java 10 reference here.

这篇关于Java Spring:Jackson 反序列化到 ZonedDateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-08 09:59