反序列化LocalDate可选Jdk8Module抛出错误

时间:2017-10-29 13:42:13

标签: java json serialization deserialization optional

我正在使用OptionalJava 8进行测试,我想通过serialize/deserialize LocalDate Json。所以我创建了自定义Object Mapper,我在其中注册了Jdk8Module

    @Bean
    public ObjectMapper objectMapperBuilder(){
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new Jdk8Module());
        return objectMapper;
    }

我的Entity课程如下:

public class Item implements Serializable{
    @JsonDeserialize(using = LocalDateDeserializer.class)
    private LocalDate insertDate;

    public Item(){}

    public Item(LocalDate insertDate) {
        this.insertDate = insertDate;
    }

    public Optional<LocalDate> getInsertDate() {
        return Optional.ofNullable(insertDate);
    }
}

但是当我从我的控制器执行GET方法时,它会抛出所有Item数据:

Resolved exception caused by Handler execution: 
org.springframework.http.converter.HttpMessageNotWritableException:
Could not write JSON: java.util.Optional cannot be cast to java.time.LocalDate;
nested exception is com.fasterxml.jackson.databind.JsonMappingException: 
java.util.Optional cannot be cast to java.time.LocalDate(through reference chain:
org.springframework.data.domain.PageImpl["content"]
->java.util.Collections$UnmodifiableRandomAccessList[0]
->com.inventory.models.Item["insertDate"])

您是否有任何线索如何改进或应该添加到我的代码中以使其有效?

1 个答案:

答案 0 :(得分:0)

对您的配置和环境有一点了解,因为您拥有类型为LocalDate的成员但是getter返回Optional<LocalDate>时会出现错误状态等混淆。

哪一个都是错误的?

我会尝试 - 基于例外 - 改变:

public Optional<LocalDate> getInsertDate() {
   return Optional.ofNullable(insertDate);
}

public LocalDate getInsertDate() {
   return Optional.ofNullable(insertDate).get();
}

OR

更改

private LocalDate insertDate;

private Optional<LocalDate> insertDate;

可能需要更改注释和/或反序列化器

@JsonDeserialize(using = LocalDateDeserializer.class)

OR

创建一个接受Oprional

的setter
public  setInsertDate(Optional<LocalDate> optLocalDate) {
    this.localDate = optLocalDate.get():
}