我正在使用Optional
对Java 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"])
您是否有任何线索如何改进或应该添加到我的代码中以使其有效?
答案 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
的setterpublic setInsertDate(Optional<LocalDate> optLocalDate) {
this.localDate = optLocalDate.get():
}