首页 > 解决方案 > 使用注解将“yyyy-MM-dd'T'HH:mm:ss”解析为 Kotlin 中的 LocalDateTime

问题描述

我想LocalDateTime使用注释将带有模板“yyyy-MM-dd'T'HH:mm:ss”的字符串解析为。

我试图解析下面的代码,但它抛出了一个错误。我应该怎么做才能修复这个错误?

代码:

SearchREQ(
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss")
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
    var departureDate: LocalDateTime,
)

错误:

Type definition error: [simple type, class java.time.LocalDateTime];
 nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
  Cannot construct instance of java.time.LocalDateTime (no Creators,
      like default construct, exist): no String-argument constructor/factory
      method to deserialize from String value ('2018-08-20T06:00:00')
at [Source: (PushbackInputStream); line: 5, column: 22]
  (through reference chain: gtd.connector.model.req.SearchREQ[\"departureDate\"])

感谢您的回答

标签: javakotlinjackson

解决方案


LocalDateTime没有String构造函数。一个可能的解决方法是:

class SearchREQ(
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss")
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
    var departureDate: Date
) {
  val departureDateTime get() =  LocalDateTime.ofInstant(departureDate.toInstant(), TimeZone.getTimeZone("UTC").toZoneId())!!
}

您还可以为LocalDateTime.


推荐阅读