我们知道前端提交字符串到后台映射为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
Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐