出現的場景:java
服務端經過springmvc寫了一個對外的接口,返回一個json字符串,其中該json帶有日期,格式爲yyyy-MM-dd HH:mm:ssweb
客戶端經過feign調用該http接口,指定返回值爲一個Dto,Dto中日期的字段爲Date類型spring
客戶端調用該接口後拋異常了。數據庫
異常以下:json
feign.codec.DecodeException: JSON parse error: Can not deserialize value of type java.util.Date from String "2018-03-07 16:18:35": not a valid representation (error: Failed to parse Date value '2018-03-07 16:18:35': Can not parse date "2018-03-07 16:18:35Z": while it seems 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: Can not deserialize value of type java.util.Date from String "2018-03-07 16:18:35": not a valid representation (error: Failed to parse Date value '2018-03-07 16:18:35': Can not parse date "2018-03-07 16:18:35Z": while it seems 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"]) at feign.SynchronousMethodHandler.decode(SynchronousMethodHandler.java:169) at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:133) at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:76) at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:103) at com.sun.proxy.$Proxy138.queryMonitorByTime(Unknown Source) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) Caused by: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Can not deserialize value of type java.util.Date from String "2018-03-07 16:18:35": not a valid representation (error: Failed to parse Date value '2018-03-07 16:18:35': Can not parse date "2018-03-07 16:18:35Z": while it seems 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: Can not deserialize value of type java.util.Date from String "2018-03-07 16:18:35": not a valid representation (error: Failed to parse Date value '2018-03-07 16:18:35': Can not parse date "2018-03-07 16:18:35Z": while it seems 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"]) at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:238) at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:223) at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:96) at org.springframework.cloud.netflix.feign.support.SpringDecoder.decode(SpringDecoder.java:59) at org.springframework.cloud.netflix.feign.support.ResponseEntityDecoder.decode(ResponseEntityDecoder.java:47) at feign.SynchronousMethodHandler.decode(SynchronousMethodHandler.java:165) ... 45 more Caused by: com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type java.util.Date from String "2018-03-07 16:18:35": not a valid representation (error: Failed to parse Date value '2018-03-07 16:18:35': Can not parse date "2018-03-07 16:18:35Z": while it seems 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"]) at com.fasterxml.jackson.databind.exc.InvalidFormatException.from(InvalidFormatException.java:74) at com.fasterxml.jackson.databind.DeserializationContext.weirdStringException(DeserializationContext.java:1410) at com.fasterxml.jackson.databind.DeserializationContext.handleWeirdStringValue(DeserializationContext.java:926) at com.fasterxml.jackson.databind.deser.std.StdDeserializer._parseDate(StdDeserializer.java:819) at com.fasterxml.jackson.databind.deser.std.StdDeserializer._parseDate(StdDeserializer.java:788) at com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateBasedDeserializer._parseDate(DateDeserializers.java:172) at com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateDeserializer.deserialize(DateDeserializers.java:259) at com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateDeserializer.deserialize(DateDeserializers.java:242) at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:504) at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:104) at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:357) at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:148) at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:287) at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:259) at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:26) at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:504) at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:104) at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:357) at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:148) at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3814) at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2938) at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:235) ... 50 more
從異常信息中咱們能夠看出,是在AbstractJackson2HttpMessageConverter類中調用了readJavaType方法以後拋的異常安全
一步一步往下深刻,咱們找到了最關鍵的地方,在DeserializationContext類的_parseDate方法中,執行了df.parse(dateStr)以後拋異常了springboot
public Date parseDate(String dateStr) throws IllegalArgumentException { try { DateFormat df = getDateFormat(); // 這行代碼報錯了 return df.parse(dateStr); } catch (ParseException e) { throw new IllegalArgumentException(String.format( "Failed to parse Date value '%s': %s", dateStr, e.getMessage())); } }
DeserializationContext是jackson的一個反序列化的一個上下文,那麼它的DateFormat是從哪來的呢?咱們再來看下getDateFormat的源碼服務器
protected DateFormat getDateFormat() { if (_dateFormat != null) { return _dateFormat; } DateFormat df = _config.getDateFormat(); _dateFormat = df = (DateFormat) df.clone(); return df; }
DateFormat又是從MapperConfig而來,咱們再看下config.getDateFormat()的源碼mvc
public final DateFormat getDateFormat() { return _base.getDateFormat(); }
咱們知道,SpringMvc就是經過AbstractJackson2HttpMessageConverter類來整合jackson的,該類維護jackson的ObjectMapper,而ObjectMapper又是經過MapperConfig來進行配置的app
因而可知,本異常就是由於ObjectMapper中的DateFormat沒法對yyyy-MM-dd HH:mm:ss格式的字符串進行轉換所致使的
異常說的值服務器返回了一個帶有日期的json,日期的形式是字符串2018-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-dd HH: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以下
import java.text.DateFormat; import java.text.FieldPosition; import java.text.ParseException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; public class MyDateFormat extends DateFormat { private DateFormat dateFormat; private SimpleDateFormat format1 = new SimpleDateFormat("yyy-MM-dd HH:mm:ss"); public MyDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; } @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { return dateFormat.format(date, toAppendTo, fieldPosition); } @Override public Date parse(String source, ParsePosition pos) { Date date = null; try { date = format1.parse(source, pos); } catch (Exception e) { date = dateFormat.parse(source, pos); } return date; } // 主要仍是裝飾這個方法 @Override public Date parse(String source) throws ParseException { Date date = null; try { // 先按個人規則來 date = format1.parse(source); } catch (Exception e) { // 不行,那就按原先的規則吧 date = dateFormat.parse(source); } return date; } // 這裏裝飾clone方法的緣由是由於clone方法在jackson中也有用到 @Override public Object clone() { Object format = dateFormat.clone(); return new MyDateFormat((DateFormat) format); } }
DateFormat有了,接下來的任務就是讓ObjectMapper使用個人這個DateFormat了,在config類中定義以下(本案例基於springboot)
@Configuration public class WebConfig { @Autowired private Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder; @Bean public MappingJackson2HttpMessageConverter MappingJsonpHttpMessageConverter() { ObjectMapper mapper = jackson2ObjectMapperBuilder.build(); // ObjectMapper爲了保障線程安全性,裏面的配置類都是一個不可變的對象 // 因此這裏的setDateFormat的內部原理實際上是建立了一個新的配置類 DateFormat dateFormat = mapper.getDateFormat(); mapper.setDateFormat(new MyDateFormat(dateFormat)); MappingJackson2HttpMessageConverter mappingJsonpHttpMessageConverter = new MappingJackson2HttpMessageConverter( mapper); return mappingJsonpHttpMessageConverter; } }
配置了上述代碼以後,問題成功解決。
查看springboot的源代碼以下:
@Configuration class JacksonHttpMessageConvertersConfiguration { @Configuration @ConditionalOnClass(ObjectMapper.class) @ConditionalOnBean(ObjectMapper.class) @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, havingValue = "jackson", matchIfMissing = true) protected static class MappingJackson2HttpMessageConverterConfiguration { @Bean @ConditionalOnMissingBean(value = MappingJackson2HttpMessageConverter.class, ignoredType = { "org.springframework.hateoas.mvc.TypeConstrainedMappingJackson2HttpMessageConverter", "org.springframework.data.rest.webmvc.alps.AlpsJsonHttpMessageConverter" }) public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter( ObjectMapper objectMapper) { return new MappingJackson2HttpMessageConverter(objectMapper); } }
默認配置爲,當spring容器中沒有MappingJackson2HttpMessageConverter這個實例的時候纔會被建立
springboot的思想是約定優於配置,也就是說,springboot默認幫咱們配好了spring mvc的Converter,若是咱們沒有自定義Converter的話,那麼框架就會幫咱們建立一個,若是咱們有自定義的話,那麼springboot就直接使用咱們所註冊的bean進行綁定
以上摘自https://blog.csdn.net/qq906627950/article/details/79503801
補充:
使用JsonFormat註解的時候須要加上時區
import com.fasterxml.jackson.annotation.JsonFormat; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
中國的時區 東8區 ,timezone="GMT+8" 是必須加上去的否則轉換後的時間和數據庫裏的時間是不同的。
補充摘自 https://blog.csdn.net/wxlhdm/article/details/45073393