【问题标题】:InvalidDefinitionException with jackson杰克逊的 InvalidDefinitionException
【发布时间】:2020-04-12 14:24:06
【问题描述】:

在 spring boot 2.2.2 中,java 11 通过 Ibm mq 接收到一个对象。

收到的对象具有 LocalDate 数据类型。

项目在 maven 中有 spring-boot-starter-web starter。

我在项目中看到了这些 jar

杰克逊数据类型 -jdk 8-2.10.1 杰克逊数据类型-jsr310-2.10.1

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class BillingEvent {
    public Long Id;
    public LocalDate billingCreatedDate;
}

在我的属性中

spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false

我得到的错误

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: 不能 构造java.time.LocalDate 的实例(没有创建者,默认 构造,存在):没有字符串参数构造函数/工厂方法 从字符串值('2019-09-02')反序列化

【问题讨论】:

标签: java spring-boot jackson deserialization localdate


【解决方案1】:

对我来说,将 setter 添加到您的 BillingEvent 就足够了,例如:

public void setBillingCreatedDate(String str) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");        
    billingCreatedDate = LocalDate.parse(str, formatter);
}

更多关于格式化的信息:String to LocalDate

基于 cmets:

这个Is there a jackson datatype module for JDK8 java.time? 可能会对你有所帮助,如果不是,它不是为了帮助,下面是一个工作 impl 的示例。 (没有任何检查左右):

public class LocalDateDeserializer extends JsonDeserializer<LocalDate> {

    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @Override
    public LocalDate deserialize(JsonParser p, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {        
          return LocalDate.parse(p.readValueAs(String.class), formatter);
    }

}

您也可以在其他地方使用它,就像在 BillingEvent 中使用它一样:

@JsonDeserialize(using = LocalDateDeserializer.class)
public LocalDate billingCreatedDate;

【讨论】:

  • 这是一种解决方法。 Jackson 能够反序列化为localDate如果转换模块已注册。
  • 我只是不明白为什么模块没有注册
猜你喜欢
  • 2018-11-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-11
  • 2011-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多