报错:
.w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.Date` from String "2022-12-13 11:22:11": not a valid representation (error: Failed to parse Date value '2022-12-13 11:22:11': Cannot parse date "2022-12-13 11:22:11": 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 "2022-12-13 11:22:11": not a valid representation (error: Failed to parse Date value '2022-12-13 11:22:11': Cannot parse date "2022-12-13 11:22:11": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSX', parsing fails (leniency? null))<EOL> at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 4, column: 14] (through reference chain: com.example.doatest.pojo.Car["createDate"])]
原因:
json序列化 类没对上, 参数接收用的Date ,传参拿到是 String 。需要做个转换。
场景:
接收参数是 Date类型
传参是 String格式 :
这个其实已经是很久很久很久之前就已经做过解决方案介绍了:
Springboot 全局日期格式化,只需要几行小代码_小目标青年的博客-CSDN博客_spring 日期格式
我还是推荐 yml配置的方案 :
#时区,默认为格林尼治时间,即少8小时,所以我们需要+8 spring.jackson.time-zone=GMT+8 #时间格式转换定义 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
轻松搞掂:
可能有人就是执拗啊,就是不想写配置,就是喜欢写代码, 然后又要全局生效转换,那怎么办?
也很好办,复制粘贴代码送给你:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.text.SimpleDateFormat;
import java.util.List;
/**
* @Author: JCccc
* @Date: 2022-4-11 18:45
* @Description:
*/
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = jackson2HttpMessageConverter.getObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
SimpleModule simpleModule = new SimpleModule();
objectMapper.registerModule(simpleModule);
jackson2HttpMessageConverter.setObjectMapper(objectMapper);
converters.add(0, jackson2HttpMessageConverter);
}
}
直接把这个类丢到你的项目里面:
轻松解决: