我们知道前端提交字符串到后台映射为Date类型可以加上@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
注解,但是这次加了还是报错
前端提交字符串到后台,出现如下错误:
while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null))
错误的大致意思就是字符串映射到Date类型失败,说我们的格式的确是符合的,但是还是映射失败
完整错误:
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.util.Date` from String "2020-07-31 07:25:29": not a valid representation (error: Failed to parse Date value '2020-07-31 07:25:29': Cannot parse date "2020-07-31 07:25:29": 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 "2020-07-31 07:25:29": not a valid representation (error: Failed to parse Date value '2020-07-31 07:25:29': Cannot parse date "2020-07-31 07:25:29": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null))
at [Source: (PushbackInputStream); line: 1, column: 87] (through reference chain: com.xb.entity.Meeting["endTime"])
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:241)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:223)
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:206)
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:157)
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:130)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:124)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:161)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:131)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at
..........
我们知道前端提交字符串到后台映射日期类型的话,加上@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
注解就行了,本人亲测SpringMVC环境可行,但此次报错的项目是SpringBoot项目,不知道是SpringBoot项目导致的转换失败还是SpringBoot项目所使用的SpringMVC版本太高才导致转换失败(这个有兴趣的小伙伴可以测试)
- 解决方案:
在application.yml
中添加如下配置
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss