我们得到一个带有日期作为json属性的HttpResponse,该日期的格式为ISO8601(例如2020-03-13T00:00:35.570 + 0000),但杰克逊抛出了以下异常:
java.time.format.DateTimeParseException: Text '2020-03-13T00:00:35.570+0000' could not be parsed at index 23
我写了以下测试(麻雀),它无法复制。 我需要知道如何解析日期。 感谢您的帮助!
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
}
}
测试使用以下依赖项:
答案 0 :(得分:4)
杰克逊不是这里的问题;如果您调用ZonedDateTime.parse("2020-03-13T00:00:35.570+0000")
,则会遇到相同的异常。根据{{3}},ZonedDateTime
使用DateTimeFormatter.ISO_ZONED_DATE_TIME
进行解析。 ISO_ZONED_DATE_TIME
是
具有偏移量和区域的日期时间,例如 '2011-12-03T10:15:30 + 01:00 [欧洲/巴黎]'
您尝试解析的值具有偏移量但没有区域,因此您需要将其转换为to the API,后者使用DateTimeFormatter.ISO_OFFSET_DATE_TIME
进行解析。 DateTimeFormatter.ISO_OFFSET_DATE_TIME
...解析具有偏移量的日期时间,例如“ 2011-12-03T10:15:30 + 01:00”。