Jackson unable to parse ISO8601

Viewed 477

We get a HttpResponse with a date as one json attribute, the date is formatted in ISO8601 (e.g. 2020-03-13T00:00:35.570+0000) but Jackson throws following Exception:

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. 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.datatype:jackson-datatype-jsr310:2.10.3
1 Answers

Jackson is not the issue here; you'd get the same exception if you called ZonedDateTime.parse("2020-03-13T00:00:35.570+0000"). According to the API, ZonedDateTime uses DateTimeFormatter.ISO_ZONED_DATE_TIME to parse. ISO_ZONED_DATE_TIME is

a date-time with offset and zone, such as '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. DateTimeFormatter.ISO_OFFSET_DATE_TIME

...parses a date-time with an offset, such as '2011-12-03T10:15:30+01:00'.

Related