DefaultHandlerExceptionResolver
.w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type
java.util.Date
from String “2020-10-12 00:00:00”: not a valid representation (error: Failed to parse Date value ‘2020-10-12 00:00:00’: Cannot parse date “2020-10-12 00:00:00”: while it seems to fit format ‘yyyy-MM-dd’T’HH:mm:ss.SSSX’, parsing fails (leniency? null)); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type
java.util.Date
from String “2020-10-12 00:00:00”: not a valid representation (error: Failed to parse Date value ‘2020-10-12 00:00:00’: Cannot parse date “2020-10-12 00:00:00”: while it seems to fit format ‘yyyy-MM-dd’T’HH:mm:ss.SSSX’, parsing fails (leniency? null))
at [Source: (PushbackInputStream); line: 1, column: 139] (through reference chain: com.cskaoyan.bean.promotion.Coupon[“startTime”])]
前端传入的是Date格式的字符串,后端使用Date
错误分析:
错误原因是日期转换失败,由于springboot默认采用jackson,而jackson只能识别以下几种日期格式:
"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
"yyyy-MM-dd";
"EEE, dd MMM yyyy HH:mm:ss zzz";
long类型的时间戳(毫秒时间戳)
不能识别yyyy-MM-dd HH:mm:ss类似格式的数据,所以转换失败。
解决办法:
- 在实体Date类型的字段上使用@JsonFormat注解格式化日期
@JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss")
- 通过下面方式取消timestamps形式
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);