java - Jackson 无法解析 ISO8601

标签 java json spring-boot jackson

我们得到一个带有日期作为 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
    }
}


测试使用以下依赖项:
  • com.fasterxml.jackson.core:jackson-databind:2.10.3
  • com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.10.3
  • 最佳答案

    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/

    相关文章:

    javascript - Json-Net、JSON日期时间解析

    java.lang.IllegalStateException : Expected BEGIN_OBJECT but was STRING at line 1 column 2 path $

    java - 在 Spring Security 中使用 UserDetails 实现登录不起作用

    java - java spring boot 微服务中的调度程序

    java - javafx 上的 sun.security.pkcs11

    java - hibernate 缓慢以获取 Postgres 连接

    Java JLabel 应该填充时却出现白色中心

    java - 将标签添加到 BoxLayout 的下一行

    android - Http Get 请求返回 html?

    java - Spring Boot application.yml 全局设置数据源属性,被忽略