Jackson将ISO8601格式的日期时间反序列化为Java8 Instant [英] Jackson deserialize ISO8601 formatted date-time into Java8 Instant
问题描述
我正在尝试使用Jackson将ISO8601格式的日期反序列化为Java8 java.time.Instant
.我向ObjectMapper注册了JavaTimeModule,并关闭了WRITE_DATES_AS_TIMESTAMPS
设置.
I'm trying to deserialize an ISO8601 formatted date into Java8 java.time.Instant
using Jackson. I registered JavaTimeModule with the ObjectMapper, and turned off the WRITE_DATES_AS_TIMESTAMPS
setting.
但是,如果尝试对2016-03-28T19:00:00.000+01:00
进行反序列化,则它将无法正常工作,因为JavaTimeModule似乎只会对具有UTC时区偏移量格式的日期时间进行反序列化(例如,2016-03-28T18:00:00.000Z
).然后,我尝试使用@JsonFormat
注释,如下所示:
However, if one tries to deserialize 2016-03-28T19:00:00.000+01:00
it will not work, because it seems that JavaTimeModule will only deserialize date-times formatted with UTC timezone offset (e.g. 2016-03-28T18:00:00.000Z
). I then tried using @JsonFormat
annotation like this:
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "UTC")
像这样:
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = JsonFormat.DEFAULT_TIMEZONE)
但是,这些都不起作用,我得到了一个例外:
However, neither of these work and I get an exception:
com.fasterxml.jackson.databind.JsonMappingException: Unsupported field: YearOfEra (through reference chain: org.example.Article["date"])
这意味着忽略时区参数,并且日期时间格式化程序不知道如何格式化不带时区的Instant.
Which implies that timezone parameter is ignored and date time formatter doesn't know how to format an Instant without a timezone.
是否有一种方法可以使用Jackson和JavaTimeModule对不在UTC时区偏移到Java 8 java.time.Instant
的UTC时区中的ISO8601字符串进行反序列化,而无需编写自定义反序列化器?
Is there a way to deserialize a ISO8601 string that's not in UTC time zone offset to Java 8 java.time.Instant
using Jackson and JavaTimeModule without writing a custom deserializer?
推荐答案
您需要通过modell类中的XXX
设置显式时区:
You need to set the explicit time zone via XXX
in your modell class:
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
(请参阅: https://docs. oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html )
这篇关于Jackson将ISO8601格式的日期时间反序列化为Java8 Instant的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!