使用时间LocalDate序列化会报错
先上实体类,测试类
@Data
public class MyTestDate {
private LocalDate now;
}
public class MyTest {
@Test
public void ttt() throws Exception {
MyTestDate myTestDate=new MyTestDate();
myTestDate.setNow(LocalDate.now());
String json = JSONUtil.obj2json(myTestDate);
System.out.println(json);
MyTestDate myTestDate1 = JSONUtil.json2pojo(json, MyTestDate.class);
System.out.println(myTestDate1);
}
}
报错
Connected to the target VM, address: '127.0.0.1:49535', transport: 'socket'
{"now":{"year":2021,"month":"JANUARY","chronology":{"id":"ISO","calendarType":"iso8601"},"dayOfMonth":21,"dayOfWeek":"THURSDAY","dayOfYear":21,"era":"CE","monthValue":1,"leapYear":false}}
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.LocalDate` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: (String)"{"now":{"year":2021,"month":"JANUARY","chronology":{"id":"ISO","calendarType":"iso8601"},"dayOfMonth":21,"dayOfWeek":"THURSDAY","dayOfYear":21,"era":"CE","monthValue":1,"leapYear":false}}"; line: 1, column: 9] (through reference chain: com.zhaolaobao.adminuser.site.controller.MyTestDate["now"])
解决方案
@JsonDeserialize(using = LocalDateDeserializer.class)
@JsonSerialize(using = LocalDateSerializer.class)
private LocalDate now;