今天在處理時間時遇到
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.Date` from String "2020-04-08": expected format "yyyy-MM-dd HH:mm:ss"; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String "2020-04-08": expected format "yyyy-MM-dd HH:mm:ss"
屬性
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date startDate;
前端傳過來的,只有年月日,需要的格式為yyyy-MM-dd HH:mm:ss
解決的方法
將前端的日期格式改為
yyyy-MM-dd HH:mm:ss
或者修改屬性的注解里pattern的值
@JsonFormat(pattern = "yyyy-MM-dd") private Date startDate;
補充:
1.@DateTimeFormat
spring自帶的,將String轉換成Date,一般前台給后台傳值時用
@DateTimeFormat(pattern=”yyyy-MM-dd”)
2.@JsonFormat
來源於jackson,將Java對象轉換成json對象和xml文檔,或將json、xml轉換成Java對象
主要用於后台傳值到前台
在屬性值上
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
3.@JSONField
來源於fastjson,主要進行JSON解析和序列化
@JSONField(format = "yyyy-MM-dd HH:mm:ss")