解析" yyyy-MM-dd' HH:mm:ss"使用注释

时间:2018-05-15 10:47:51

标签: java kotlin jackson

我想用模板解析String" yyyy-MM-dd' H&H:mm:ss"使用注释到LocalDateTime

我试图通过下面的代码进行解析,但它却抛出了一个错误。 我该怎么做才能解决这个错误?

代码:

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\"])

感谢您的回答

1 个答案:

答案 0 :(得分:0)

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实现自定义反序列化器。