我需要在单个代码中将以下两个格式反序列化为java.time.Instant
2020-04-23T10:51:24.238+01:00
和
2019-11-11T15:44:10.201Z
在第一种情况下我遇到了以下错误
嵌套异常是org.springframework.http.converter.HttpMessageNotReadableException:JSON解析错误:无法从字符串“2020-04-23T10:51:24.238+”反序列化java.time.Instant
类型的值01:00": com.fasterxml.jackson.databind.exc.InvalidFormatException: 无法从字符串 "2020-04-23T10:51:24.238+01:00 反序列化 java.time.Instant
类型的值": 无法反序列化 java.time.Instant: (java.time.format.DateTimeParseException) 无法在索引 23 处解析文本 '2020-04-23T10:51:24.238+01:00'
有什么解决办法吗?
还有什么方法可以将 java.util.Date
反序列化为 java.time.Instant
注意:它是一个 API 响应,我无法在反序列化类(即消费者)中使用 Date
最佳答案
String dateString = "2020-04-23T10:51:24.238+01:00";
Instant deserializedInstant = DateTimeFormatter.ISO_OFFSET_DATE_TIME
.parse(dateString, Instant::from);
System.out.println(deserializedInstant);
输出是:
2020-04-23T09:51:24.238Z
它也适用于您的其他字符串:
String dateString = "2019-11-11T15:44:10.201Z";
2019-11-11T15:44:10.201Z
您的 JSON 库可能有更优雅的解决方案。如果没有,您可以将以上内容包装在自定义 JSON 反序列化器中。
关于java - 将 java 日期反序列化为 Instant,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61724859/