[英]Jackson unable to parse ISO8601
我們得到一個帶有日期作為一個 json 屬性的 HttpResponse,日期格式為 ISO8601(例如 2020-03-13T00:00:35.570+0000),但 Jackson 拋出以下異常:
java.time.format.DateTimeParseException: Text '2020-03-13T00:00:35.570+0000' could not be parsed at index 23
我已經編寫了以下無法重現的測試(spock)。 我需要知道如何解析日期。 謝謝你的幫助!
class TestJackson extends Specification{
def 'test date format'(){
given:
def jsonString = """{"myDate":"2020-03-13T00:00:35.570+0000"}"""
and:
def objectMapper = new ObjectMapper()
.registerModule(new JavaTimeModule())
.enable(SerializationFeature.INDENT_OUTPUT)
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
when:
def resp = objectMapper.readValue(jsonString, Response)
then:
resp.myDate != null
}
@Data
@NoArgsConstructor
@AllArgsConstructor
static class Response {
ZonedDateTime myDate
}
}
測試使用以下依賴項:
傑克遜不是這里的問題; 如果您調用ZonedDateTime.parse("2020-03-13T00:00:35.570+0000")
您會得到相同的異常。 根據API , ZonedDateTime
使用DateTimeFormatter.ISO_ZONED_DATE_TIME
來解析。 ISO_ZONED_DATE_TIME
是
帶有偏移量和區域的日期時間,例如 '2011-12-03T10:15:30+01:00[Europe/Paris]'
您嘗試解析的值具有偏移量但沒有區域,因此您需要將其轉換為OffsetDateTime
,它使用DateTimeFormatter.ISO_OFFSET_DATE_TIME
進行解析。 DateTimeFormatter.ISO_OFFSET_DATE_TIME
...解析具有偏移量的日期時間,例如“2011-12-03T10:15:30+01:00”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.