【问题标题】:Deserialize "Zulu" time in ISO8601 format in jackson在杰克逊中以 ISO8601 格式反序列化“Zulu”时间
【发布时间】:2017-04-12 06:23:27
【问题描述】:

我需要使用 Jackson 将格式 2016-11-28T10:34:25.097Z 的时间反序列化为 Java8 的 ZonedDateTime。

我相信我正确配置了 ObjectMapper(一种工厂方法):

 @Bean
ObjectMapper getObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    // some other config...
    objectMapper.registerModule(new JavaTimeModule());
    return objectMapper;
}

我的 DTO 代码中有一个字段

  @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
private ZonedDateTime updatedAt;

当我尝试用 Jackson 解析这个时,我得到了

 java.lang.IllegalArgumentException: Can not deserialize value of type java.time.ZonedDateTime 
 from String "2016-11-28T10:34:25.097Z": Text '2016-11-28T10:34:25.097Z' could not be parsed,
 unparsed text found at index 23  at [Source: N/A; line: -1, column: -1]  

没有@JsonFormat 问题仍然存在。

我怎么可能克服这个?

【问题讨论】:

    标签: java json jackson zoneddatetime


    【解决方案1】:

    问题可能与模式中的“Z”有关。它不允许在日期时间值中使用文字“Z”。改用“X”。

      @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX")
    

    【讨论】:

      【解决方案2】:

      我需要像你一样以 ISO8601 Zulu 格式序列化/反序列化日期 2016-11-28T10:34:25.097Z

      我选择使用 ISO8601DateFormat 更改 ObjectMapper 中的日期格式化程序

      喜欢这个

      @Bean
      ObjectMapper getObjectMapper() {
          ObjectMapper objectMapper = new ObjectMapper();
          // some other config...
          objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
          objectMapper.setDateFormat(new ISO8601DateFormat());
          return objectMapper;
      }
      

      【讨论】:

        【解决方案3】:

        在我的选项中,ISO 8601 的以下 JsonFormat

        @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
        

        要好得多,因为这种格式阅读起来更直观,并且允许像 ACST 这样的时区,其 UTC 偏移量也为 +09:30。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-04-07
          • 1970-01-01
          • 2019-07-05
          • 1970-01-01
          • 2012-11-19
          • 2016-10-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多