tom*_*omi 3 java json spring-boot java-time
我正在使用 Java 11、Spring Boot 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;
Run Code Online (Sandbox Code Playgroud)
但我收到以下错误:
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"])]
Run Code Online (Sandbox Code Playgroud)
Arv*_*ash 11
那里有两个您的代码
java.time.LocalDateTime无法反序列化字符串“2019-10-21T13:00:00+02:00”中类型的值:无法反序列化 java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2019-10-21T13:00 :00+02:00' 无法解析,在索引 19 处找到未解析的文本
如果你分析一下错误信息,你会发现它清楚地告诉你索引19处有问题。
2019-10-21T13:00:00+02:00
// index 19 ----> ^
Run Code Online (Sandbox Code Playgroud)
而且,问题是LocalDateTime不支持时区。下面给出了java.time 类型的概述,您可以看到与日期时间字符串匹配的类型是OffsetDateTime因为它的区域偏移量为+02:00小时。
更改您的声明如下:
private OffsetDateTime startTime;
Run Code Online (Sandbox Code Playgroud)
您需要使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
2019-10-21T13:00+02:00
Run Code Online (Sandbox Code Playgroud)
从Trail: Date Time中了解有关现代日期时间 API 的更多信息。
另请参阅RFC3339 -互联网上的日期和时间:时间戳
本文档定义了用于 Internet 协议的日期和时间格式,该格式是ISO 8601标准
的概要文件,用于 使用公历表示日期和时间。
| 归档时间: |
|
| 查看次数: |
8265 次 |
| 最近记录: |