繁体   English   中英

Spring 启动:JSON 将带时区的日期和时间反序列化为 LocalDateTime

[英]Spring boot: JSON deserialize date and time with time zone to LocalDateTime

我正在使用 Java 11、Spring 启动 2.2.6.RELEASE。 如何将“2019-10-21T13:00:00+02:00”反序列化为 LocalDateTime?

到目前为止尝试过:

  @JsonSerialize(using = LocalDateTimeSerializer.class)
  @JsonDeserialize(using = LocalDateTimeDeserializer.class)
  @DateTimeFormat(iso = ISO.DATE_TIME)
  @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ssZ")
  private LocalDateTime startTime;

但我收到以下错误:

2021-02-19 07:45:41.402  WARN 801117 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.time.LocalDateTime` from String "2019-10-21T13:00:00+02:00": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2019-10-21T13:00:00+02:00' could not be parsed, unparsed text found at index 19; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDateTime` from String "2019-10-21T13:00:00+02:00": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2019-10-21T13:00:00+02:00' could not be parsed, unparsed text found at index 19
 at [Source: (PushbackInputStream); line: 2, column: 18] (through reference chain: example.app.dto.DtoRequest["startTime"])]

您的代码有两个问题:

1.使用错误的类型

java.time.LocalDateTime无法获得Z93F725A0742FE1C889F4.LOCALDATETIME的值的价值。 10-21T13:00:00+02:00' 无法解析,在索引 19 处找到未解析的文本

如果你分析错误信息,你会发现它清楚地告诉你索引 19 有问题。

2019-10-21T13:00:00+02:00
// index 19 ---->  ^  

而且,问题是LocalDateTime不支持时区。 下面给出了 java.time 类型的概述,您可以看到与您的日期时间字符串匹配的类型是OffsetDateTime ,因为它的区域偏移量为+02:00小时。

在此处输入图像描述

更改您的声明如下:

private OffsetDateTime startTime;

2.使用错误的格式

您需要将XXX用于偏移部分,即您的格式应为uuuu-MM-dd'T'HH:m:ssXXX 如果你想坚持Z ,你需要使用ZZZZZ 查看DateTimeFormatter的文档页面以获取更多详细信息。

演示:

import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        String strDateTime = "2019-10-21T13:00:00+02:00";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:m:ssXXX");
        OffsetDateTime odt = OffsetDateTime.parse(strDateTime, dtf);
        System.out.println(odt);
    }
}

Output:

2019-10-21T13:00+02:00

Trail: Date Time了解有关现代日期时间 API 的更多信息。

同样相关的还有RFC3339 - Internet 上的日期和时间:时间戳

本文档定义了用于 Internet 的日期和时间格式
协议是ISO 8601标准的配置文件
使用公历表示日期和时间。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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