JSON parse error: Cannot deserialize value of type `java.util.Date` from String not a valid representation

发布时间 2023-03-22 21:11:09作者: IQiuq

日志

Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.Date` from String "2023-03-21 09:12:33": not a valid representation (error: Failed to parse Date value '2023-03-21 09:12:33': Cannot parse date "2023-03-21 09:12:33": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null)); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String "2023-03-21 09:12:33": not a valid representation (error: Failed to parse Date value '2023-03-21 09:12:33': Cannot parse date "2023-03-21 09:12:33": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null))
 at [Source: (PushbackInputStream); line: 4, column: 21] (through reference chain: com.qiu.fragment.dto.GoodsInfoDto["productionDate"])]

接口请求入参的Bean
img

请求接口传参如下:

{
  "name": "",
  "price": 0.0,
  "productionDate": "2023-03-21 09:12:33",
  "expireDate": "2023-03-21"
}

接口请求出现:Cannot deserialize value of type java.util.Date from String,无法将字符串反序列化为Date类型,使用@DateTimeFormat(patter="yyyy-MM-dd")格式化也会失效。

这里并不是因为@DateTimeFormat注解导致的问题,而且因为@RequestBody注解会JSON序列化成Bean,然后请求接口传参的productionDate是字符串类型,对应的Bean是Date类型,就出现转换异常。

img

解决

使用@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")注解,完美解决。
img

对于@DateTimeFormat@JsonFormat这两个注解,网上查到的都是,@DateTimeFormat是后端接收前端的传入日期进行格式化,@JsonFormat是后端从数据库查到的日期格式化后返回给前端。

但我使用@DateTimeFormat并没有格式化也没有类型转换,疑惑不解???