日期格式序列化问题
场景:使用avue的表单组件,插入数据,选择插入时间的时候报错
JSON parse error: Cannot deserialize value of type `java.time.LocalDateTime` from String "2023-02-10T07:00:49.000Z": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2023-02-10T07:00:49.000Z' could not be parsed at index 10; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDateTime` from String "2023-02-10T07:00:49.000Z": Failed to deserialize java.time.LocalDateTime: (java.time.format.DateTimeParseException) Text '2023-02-10T07:00:49.000Z' could not be parsed at index 10 at [Source: (PushbackInputStream); line: 1, column: 78] (through reference chain: org.springblade.modules.demo.entity.Blog["time"])
这里报错的大致意思是 localdatetime的数据类型生成的时间字符串是 2023-02-10T07:00:49.000Z 中间有个 T ,最后还有一个Z 不能被反序列化,那么解决思路有2个
让时间生成的时候不带 T 和 Z
找转换器能够转换这个时间格式
这里使用了第二个思路
引入依赖
环境:java8,mysql8,时间字段的数据类型是TIMESTAMP
说明:TIMESTAMP 和 DATETIME 的选择不影响结果,我测试的结果是这样的
解决方案:
实体类的 时间 字段上添加注解
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
//private LocalDateTime time;
备注 导包别导错了