我们得到一个带有日期作为 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
}
}
测试使用以下依赖项:
最佳答案
jackson 不是这里的问题;如果你调用 ZonedDateTime.parse("2020-03-13T00:00:35.570+0000")
,你会得到同样的异常.根据 to the API , ZonedDateTime
用途 DateTimeFormatter.ISO_ZONED_DATE_TIME
解析。 ISO_ZONED_DATE_TIME
是
a date-time with offset and zone, such as '2011-12-03T10:15:30+01:00[Europe/Paris]'
您尝试解析的值具有偏移量但没有区域,因此您需要将其转换为
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'.
关于java - Jackson 无法解析 ISO8601,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60865953/