1、问题排查
出现的场景:
服务端通过springmvc写了一个对外的接口,返回一个json字符串,其中该json带有日期,格式为yyyy-MM-dd HH:mm:ss
客户端通过feign调用该http接口,指定返回值为一个Dto,Dto中日期的字段为Date类型
客户端调用该接口后抛异常了。
报错异常如下:
feign.codec.DecodeException: JSON parse error: Cannotdeserialize valueoftype java.util.Date from String "-03-07 16:18:35":notavalid representation (error: Failed to parse Date value '-03-07 16:18:35': Cannotparse date "-03-07 16:18:35Z":whileitseems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS'Z'', parsing fails (leniency? null)); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannotdeserialize valueoftype java.util.Date from String "-03-07 16:18:35":notavalid representation (error: Failed to parse Date value '-03-07 16:18:35': Cannotparse date "-03-07 16:18:35Z":whileitseems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS'Z'', parsing fails (leniency? null))at[Source: java.io.PushbackInputStream@4615bc00; line: 1, column: 696] (through reference chain: com.RestfulDataBean["data"]->java.util.ArrayList[0]->com.entity.XxxDto["createTime"])atfeign.SynchronousMethodHandler.decode(SynchronousMethodHandler.java:169)atfeign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:133)atfeign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:76)atfeign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:103)atcom.sun.proxy.$Proxy138.queryMonitorByTime(Unknown Source)atorg.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)atorg.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)atorg.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)atorg.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)atorg.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)atorg.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)atorg.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)atorg.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)atsun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)atsun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)atsun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)atjava.lang.reflect.Method.invoke(Method.java:498)atorg.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)atorg.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)atorg.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)atorg.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)atorg.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)atorg.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)atorg.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)atorg.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)atorg.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)atorg.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)atorg.junit.runners.ParentRunner$3.run(ParentRunner.java:290)atorg.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)atorg.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)atorg.junit.runners.ParentRunner.access$000(ParentRunner.java:58)atorg.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)atorg.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)atorg.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)atorg.junit.runners.ParentRunner.run(ParentRunner.java:363)atorg.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)atorg.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)atorg.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)atorg.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)atorg.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)atorg.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)atorg.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)Causedby: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannotdeserialize valueoftype java.util.Date from String "-03-07 16:18:35":notavalid representation (error: Failed to parse Date value '-03-07 16:18:35': Cannotparse date "-03-07 16:18:35Z":whileitseems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS'Z'', parsing fails (leniency? null)); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannotdeserialize valueoftype java.util.Date from String "-03-07 16:18:35":notavalid representation (error: Failed to parse Date value '-03-07 16:18:35': Cannotparse date "-03-07 16:18:35Z":whileitseems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS'Z'', parsing fails (leniency? null))at[Source: java.io.PushbackInputStream@4615bc00; line: 1, column: 696] (through reference chain: com.RestfulDataBean["data"]->java.util.ArrayList[0]->com.XxxDto["createTime"])atorg.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:238)atorg.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:223)atorg.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:96)atorg.flix.feign.support.SpringDecoder.decode(SpringDecoder.java:59)atorg.flix.feign.support.ResponseEntityDecoder.decode(ResponseEntityDecoder.java:47)atfeign.SynchronousMethodHandler.decode(SynchronousMethodHandler.java:165)... 45 moreCausedby: com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannotdeserialize valueoftype java.util.Date from String "-03-07 16:18:35":notavalid representation (error: Failed to parse Date value '-03-07 16:18:35': Cannotparse date "-03-07 16:18:35Z":whileitseems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS'Z'', parsing fails (leniency? null))at[Source: java.io.PushbackInputStream@4615bc00; line: 1, column: 696] (through reference chain: com.RestfulDataBean["data"]->java.util.ArrayList[0]->com.XxxDto["createTime"])atcom.fasterxml.jackson.databind.exc.InvalidFormatException.from(InvalidFormatException.java:74)atcom.fasterxml.jackson.databind.DeserializationContext.weirdStringException(DeserializationContext.java:1410)atcom.fasterxml.jackson.databind.DeserializationContext.handleWeirdStringValue(DeserializationContext.java:926)atcom.fasterxml.jackson.databind.deser.std.StdDeserializer._parseDate(StdDeserializer.java:819)atcom.fasterxml.jackson.databind.deser.std.StdDeserializer._parseDate(StdDeserializer.java:788)atcom.fasterxml.jackson.databind.deser.std.DateDeserializers$DateBasedDeserializer._parseDate(DateDeserializers.java:172)atcom.fasterxml.jackson.databind.deser.std.DateDeserializers$DateDeserializer.deserialize(DateDeserializers.java:259)atcom.fasterxml.jackson.databind.deser.std.DateDeserializers$DateDeserializer.deserialize(DateDeserializers.java:242)atcom.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:504)atcom.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:104)atcom.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:357)atcom.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:148)atcom.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:287)atcom.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:259)atcom.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:26)atcom.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:504)atcom.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:104)atcom.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:357)atcom.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:148)atcom.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3814)atcom.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2938)atorg.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:235)... 50 more
从异常信息中我们可以看出,是在AbstractJackson2HttpMessageConverter类中调用了readJavaType方法之后抛的异常
一步一步往下深入,我们找到了最关键的地方,在DeserializationContext类的_parseDate方法中,执行了df.parse(dateStr)之后抛异常了
publicDateparseDate(String dateStr)throwsIllegalArgumentException{try{DateFormat df = getDateFormat();// 这行代码报错了returndf.parse(dateStr);}catch(ParseException e) {thrownewIllegalArgumentException(String.format("Failed to parse Date value '%s': %s", dateStr, e.getMessage()));}}
DeserializationContext是jackson的一个反序列化的一个上下文,那么它的DateFormat是从哪来的呢?我们再来看下getDateFormat的源码
protectedDateFormatgetDateFormat(){if(_dateFormat !=null) {return_dateFormat;}DateFormat df = _config.getDateFormat();_dateFormat = df = (DateFormat) df.clone();returndf;}
DateFormat又是从MapperConfig而来,我们再看下config.getDateFormat()的源码
publicfinalDateFormatgetDateFormat() {return_base.getDateFormat(); }
我们知道,SpringMvc就是通过AbstractJackson2HttpMessageConverter类来整合jackson的,该类维护jackson的ObjectMapper,而ObjectMapper又是通过MapperConfig来进行配置的
由此可见,本异常就是因为ObjectMapper中的DateFormat无法对yyyy-MM-dd HH:mm:ss格式的字符串进行转换所导致的
2、问题处理
异常说的值服务器返回了一个带有日期的json,日期的形式是字符串-03-07 16:18:35,jackson无法将该字符串转成一个Date对象,网上查资料,上面说的是jackson只支持以下几种日期格式:
"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
"yyyy-MM-dd";
"EEE, dd MMM yyyy HH:mm:ss zzz";
long类型的时间戳
去掉服务端的以下两个配置,让日期返回时间戳,结果就没报错了
#spring.jackson.date-format=yyyy-MM-ddHH:mm:ss#spring.jackson.time-zone=Asia/Chongqing
由于服务端在其他的地方有可能和这里的配置耦合了,也就是说其他地方有可能要用到的是yyyy-MM-dd HH:mm:ss这一日期格式而不是时间戳的格式,所以这个配置肯定是不能修改的。
jackson竟然不支持yyyy-MM-dd HH:mm:ss的这种格式,肯定很不爽啦,所以下面就要开始来研究怎么让jackson支持这种格式了。
要让jackson支持这种格式,那么就必须修改ObjectMapper中的DateFormat,因为在ObjectMapper中,DateFormat的默认实现类是StdDateFormat,StdDateFormat也就只兼容了我们上述所说的几种格式
首先我们先使用装饰模式来创建一个支持yyyy-MM-dd HH:mm:ss格式的DateFormat如下
importjava.text.DateFormat;importjava.text.FieldPosition;importjava.text.ParseException;importjava.text.ParsePosition;importjava.text.SimpleDateFormat;importjava.util.Date;publicclassMyDateFormatextendsDateFormat{privateDateFormat dateFormat;privateSimpleDateFormat format1 =newSimpleDateFormat("yyy-MM-dd HH:mm:ss");publicMyDateFormat(DateFormat dateFormat) {this.dateFormat = dateFormat;}@OverridepublicStringBufferformat(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {returndateFormat.format(date, toAppendTo, fieldPosition);}@OverridepublicDateparse(String source, ParsePosition pos) {Date date =null;try{date = format1.parse(source, pos);}catch(Exception e) {date = dateFormat.parse(source, pos);}returndate;}// 主要还是装饰这个方法@OverridepublicDateparse(String source)throwsParseException {Date date =null;try{// 先按我的规则来date = format1.parse(source);}catch(Exception e) {// 不行,那就按原先的规则吧date = dateFormat.parse(source);}returndate;}// 这里装饰clone方法的原因是因为clone方法在jackson中也有用到@OverridepublicObjectclone() {Object format = dateFormat.clone();returnnewMyDateFormat((DateFormat) format);}}
DateFormat有了,接下来的任务就是让ObjectMapper使用我的这个DateFormat了,在config类中定义如下(本案例基于springboot)
@ConfigurationpublicclassWebConfig{@AutowiredprivateJackson2ObjectMapperBuilder jackson2ObjectMapperBuilder;@BeanpublicMappingJackson2HttpMessageConverterMappingJsonpHttpMessageConverter() {ObjectMapper mapper = jackson2ObjectMapperBuilder.build();// ObjectMapper为了保障线程安全性,里面的配置类都是一个不可变的对象// 所以这里的setDateFormat的内部原理其实是创建了一个新的配置类DateFormat dateFormat = mapper.getDateFormat();mapper.setDateFormat(newMyDateFormat(dateFormat));MappingJackson2HttpMessageConverter mappingJsonpHttpMessageConverter =newMappingJackson2HttpMessageConverter(mapper);returnmappingJsonpHttpMessageConverter;}}
配置了上述代码之后,问题成功解决。
3、为什么往spring容器中注入MappingJackson2HttpMessageConverter,springMvc就会用这个Converter呢?
查看springboot的源代码如下:
@ConfigurationclassJacksonHttpMessageConvertersConfiguration{@Configuration@ConditionalOnClass(ObjectMapper.class)@ConditionalOnBean(ObjectMapper.class)@ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, havingValue = "jackson", matchIfMissing =true)protectedstaticclassMappingJackson2HttpMessageConverterConfiguration{@Bean@ConditionalOnMissingBean(value = MappingJackson2HttpMessageConverter.class, ignoredType = {"org.springframework.hateoas.mvc.TypeConstrainedMappingJackson2HttpMessageConverter","org.springframework.data.rest.webmvc.alps.AlpsJsonHttpMessageConverter" })publicMappingJackson2HttpMessageConvertermappingJackson2HttpMessageConverter(ObjectMapper objectMapper) {returnnewMappingJackson2HttpMessageConverter(objectMapper);}}
默认配置为,当spring容器中没有MappingJackson2HttpMessageConverter这个实例的时候才会被创建
springboot的思想是约定优于配置,也就是说,springboot默认帮我们配好了spring mvc的Converter,如果我们没有自定义Converter的话,那么框架就会帮我们创建一个,如果我们有自定义的话,那么springboot就直接使用我们所注册的bean进行绑定
Spring Mvc使用Jackson进行json转对象时 遇到的字符串转日期的异常处理(Can not deserialize value of type Date from String)