本文主要是介绍SpringMVC日期参数转换问题Can not deserialize value of type java.util.Date from String 2018-07-19 15:59:34,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问题分析
报错日志
Caused by: com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserializevalue of type java.util.Date from Stringto parse Date value '2018-07-19 15:59:34': Can not parse date "2018-07-19 15:59:34": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS',
parsing fails (leniency? null))
问题分析:
前端传过来的日期格式为yyyy-MM-dd HH:mm:ss.SSS由于前端传递过来的是日期字符串格式的值,而SpringMVC无法将日期字符串格式的值解析为日期格式
解决方案一
新增一个类继承 org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter 父类 覆写父类的configureMessageConverters方法,增加MappingJackson2HttpMessageConverter类型的对象值
@Component
class WebConfigurer extends WebMvcConfigurerAdapter {@Overridepublic void configureMessageConverters(List < HttpMessageConverter < ? > > converters) {MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();//设置日期格式ObjectMapper objectMapper = new ObjectMapper();SimpleDateFormat smt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");objectMapper.setDateFormat(smt);mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);//设置中文编码格式List<MediaType> list = new ArrayList<MediaType>();list.add(MediaType.APPLICATION_JSON_UTF8);mappingJackson2HttpMessageConverter.setSupportedMediaTypes(list);converters.add(mappingJackson2HttpMessageConverter);super.configureMessageConverters(converters);}
}
方案二
@Configuration
public class WebWeixinConfig {@Beanpublic MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();//设置日期格式ObjectMapper objectMapper = new ObjectMapper();SimpleDateFormat smt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");objectMapper.setDateFormat(smt);mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);//设置中文编码格式List<MediaType> list = new ArrayList<MediaType>();list.add(MediaType.APPLICATION_JSON_UTF8);mappingJackson2HttpMessageConverter.setSupportedMediaTypes(list);return mappingJackson2HttpMessageConverter;}}
这篇关于SpringMVC日期参数转换问题Can not deserialize value of type java.util.Date from String 2018-07-19 15:59:34的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!