Java Spring:Jackson 反序列化到 ZonedDateTime

编程入门 行业动态 更新时间:2024-10-10 19:17:53
本文介绍了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

本文发布于:2023-10-29 00:52:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538222.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列化   Spring   Java   ZonedDateTime   Jackson

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!