简体   繁体   English

Jackson 无法解析 ISO8601

[英]Jackson unable to parse ISO8601

We get a HttpResponse with a date as one json attribute, the date is formatted in ISO8601 (eg 2020-03-13T00:00:35.570+0000) but Jackson throws following Exception:我们得到一个带有日期作为一个 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

I`ve written the following Test (spock) which fails reproduceable.我已经编写了以下无法重现的测试(spock)。 I need to know how to parse the date.我需要知道如何解析日期。 Thanks for your help!谢谢你的帮助!

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
    }
}

The Test uses following Dependencies:测试使用以下依赖项:

  • com.fasterxml.jackson.core:jackson-databind:2.10.3 com.fasterxml.jackson.core:jackson-databind:2.10.3
  • com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.10.3 com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.10.3

Jackson is not the issue here;杰克逊不是这里的问题; you'd get the same exception if you called ZonedDateTime.parse("2020-03-13T00:00:35.570+0000") .如果您调用ZonedDateTime.parse("2020-03-13T00:00:35.570+0000")您会得到相同的异常。 According to the API , ZonedDateTime uses DateTimeFormatter.ISO_ZONED_DATE_TIME to parse.根据APIZonedDateTime使用DateTimeFormatter.ISO_ZONED_DATE_TIME来解析。 ISO_ZONED_DATE_TIME is ISO_ZONED_DATE_TIME

a date-time with offset and zone, such as '2011-12-03T10:15:30+01:00[Europe/Paris]'带有偏移量和区域的日期时间,例如 '2011-12-03T10:15:30+01:00[Europe/Paris]'

The value you were trying to parse has an offset but no zone so you need to convert it to OffsetDateTime , which uses DateTimeFormatter.ISO_OFFSET_DATE_TIME to parse.您尝试解析的值具有偏移量但没有区域,因此您需要将其转换为OffsetDateTime ,它使用DateTimeFormatter.ISO_OFFSET_DATE_TIME进行解析。 DateTimeFormatter.ISO_OFFSET_DATE_TIME

...parses a date-time with an offset, such as '2011-12-03T10:15:30+01:00'. ...解析具有偏移量的日期时间,例如“2011-12-03T10:15:30+01:00”。

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

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