当前位置:   article > 正文

Spring Mvc使用Jackson进行json转对象时,遇到的字符串转日期的异常处理(Can not deserialize value of type Date from String)_springmvc cannot deserialize value of type `java.s

springmvc cannot deserialize value of type `java.sql.date`

1、问题排查

  • 出现的场景:

    • 服务端通过springmvc写了一个对外的接口,返回一个json字符串,其中该json带有日期,格式为yyyy-MM-dd HH:mm:ss

    • 客户端通过feign调用该http接口,指定返回值为一个Dto,Dto中日期的字段为Date类型

    • 客户端调用该接口后抛异常了。

  • 报错异常如下:

    1. 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))
    2. at [Source: java.io.PushbackInputStream@4615bc00; line: 1, column: 696] (through reference chain: com.RestfulDataBean["data"]->java.util.ArrayList[0]->com.entity.XxxDto["createTime"])
    3. at feign.SynchronousMethodHandler.decode(SynchronousMethodHandler.java:169)
    4. at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:133)
    5. at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:76)
    6. at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:103)
    7. at com.sun.proxy.$Proxy138.queryMonitorByTime(Unknown Source)
    8. at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    9. at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)
    10. at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    11. at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    12. at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    13. at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    14. at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    15. at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)
    16. at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    17. at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    18. at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    19. at java.lang.reflect.Method.invoke(Method.java:498)
    20. at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    21. at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    22. at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    23. at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    24. at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    25. at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    26. at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    27. at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    28. at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    29. at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    30. at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    31. at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    32. at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    33. at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    34. at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    35. at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    36. at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    37. at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    38. at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    39. at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    40. at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    41. at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    42. at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    43. at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    44. at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
    45. 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))
    46. at [Source: java.io.PushbackInputStream@4615bc00; line: 1, column: 696] (through reference chain: com.RestfulDataBean["data"]->java.util.ArrayList[0]->com.XxxDto["createTime"])
    47. at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:238)
    48. at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:223)
    49. at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:96)
    50. at org.springframework.cloud.netflix.feign.support.SpringDecoder.decode(SpringDecoder.java:59)
    51. at org.springframework.cloud.netflix.feign.support.ResponseEntityDecoder.decode(ResponseEntityDecoder.java:47)
    52. at feign.SynchronousMethodHandler.decode(SynchronousMethodHandler.java:165)
    53. ... 45 more
    54. 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))
    55. at [Source: java.io.PushbackInputStream@4615bc00; line: 1, column: 696] (through reference chain: com.RestfulDataBean["data"]->java.util.ArrayList[0]->com.XxxDto["createTime"])
    56. at com.fasterxml.jackson.databind.exc.InvalidFormatException.from(InvalidFormatException.java:74)
    57. at com.fasterxml.jackson.databind.DeserializationContext.weirdStringException(DeserializationContext.java:1410)
    58. at com.fasterxml.jackson.databind.DeserializationContext.handleWeirdStringValue(DeserializationContext.java:926)
    59. at com.fasterxml.jackson.databind.deser.std.StdDeserializer._parseDate(StdDeserializer.java:819)
    60. at com.fasterxml.jackson.databind.deser.std.StdDeserializer._parseDate(StdDeserializer.java:788)
    61. at com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateBasedDeserializer._parseDate(DateDeserializers.java:172)
    62. at com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateDeserializer.deserialize(DateDeserializers.java:259)
    63. at com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateDeserializer.deserialize(DateDeserializers.java:242)
    64. at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:504)
    65. at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:104)
    66. at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:357)
    67. at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:148)
    68. at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:287)
    69. at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:259)
    70. at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:26)
    71. at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:504)
    72. at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:104)
    73. at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:357)
    74. at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:148)
    75. at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3814)
    76. at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2938)
    77. at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:235)
    78. ... 50 more
  • 从异常信息中我们可以看出,是在AbstractJackson2HttpMessageConverter类中调用了readJavaType方法之后抛的异常

  • 一步一步往下深入,我们找到了最关键的地方,在DeserializationContext类的_parseDate方法中,执行了df.parse(dateStr)之后抛异常了

    1. public Date parseDate(String dateStr) throws IllegalArgumentException
    2. {
    3. try {
    4. DateFormat df = getDateFormat();
    5. // 这行代码报错了
    6. return df.parse(dateStr);
    7. } catch (ParseException e) {
    8. throw new IllegalArgumentException(String.format(
    9. "Failed to parse Date value '%s': %s", dateStr, e.getMessage()));
    10. }
    11. }
  • DeserializationContext是jackson的一个反序列化的一个上下文,那么它的DateFormat是从哪来的呢?我们再来看下getDateFormat的源码

    1. protected DateFormat getDateFormat()
    2. {
    3. if (_dateFormat != null) {
    4. return _dateFormat;
    5. }
    6. DateFormat df = _config.getDateFormat();
    7. _dateFormat = df = (DateFormat) df.clone();
    8. return df;
    9. }
  • DateFormat又是从MapperConfig而来,我们再看下config.getDateFormat()的源码

    public final DateFormat getDateFormat() { return _base.getDateFormat(); }
    
  • 我们知道,SpringMvc就是通过AbstractJackson2HttpMessageConverter类来整合jackson的,该类维护jackson的ObjectMapper,而ObjectMapper又是通过MapperConfig来进行配置的

  • 由此可见,本异常就是因为ObjectMapper中的DateFormat无法对yyyy-MM-dd HH:mm:ss格式的字符串进行转换所导致的

2、问题处理

  • 异常说的值服务器返回了一个带有日期的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类型的时间戳

  • 去掉服务端的以下两个配置,让日期返回时间戳,结果就没报错了

    1. #spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
    2. #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如下

    1. import java.text.DateFormat;
    2. import java.text.FieldPosition;
    3. import java.text.ParseException;
    4. import java.text.ParsePosition;
    5. import java.text.SimpleDateFormat;
    6. import java.util.Date;
    7. public class MyDateFormat extends DateFormat {
    8. private DateFormat dateFormat;
    9. private SimpleDateFormat format1 = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
    10. public MyDateFormat(DateFormat dateFormat) {
    11. this.dateFormat = dateFormat;
    12. }
    13. @Override
    14. public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
    15. return dateFormat.format(date, toAppendTo, fieldPosition);
    16. }
    17. @Override
    18. public Date parse(String source, ParsePosition pos) {
    19. Date date = null;
    20. try {
    21. date = format1.parse(source, pos);
    22. } catch (Exception e) {
    23. date = dateFormat.parse(source, pos);
    24. }
    25. return date;
    26. }
    27. // 主要还是装饰这个方法
    28. @Override
    29. public Date parse(String source) throws ParseException {
    30. Date date = null;
    31. try {
    32. // 先按我的规则来
    33. date = format1.parse(source);
    34. } catch (Exception e) {
    35. // 不行,那就按原先的规则吧
    36. date = dateFormat.parse(source);
    37. }
    38. return date;
    39. }
    40. // 这里装饰clone方法的原因是因为clone方法在jackson中也有用到
    41. @Override
    42. public Object clone() {
    43. Object format = dateFormat.clone();
    44. return new MyDateFormat((DateFormat) format);
    45. }
    46. }
  • DateFormat有了,接下来的任务就是让ObjectMapper使用我的这个DateFormat了,在config类中定义如下(本案例基于springboot)

    1. @Configuration
    2. public class WebConfig {
    3. @Autowired
    4. private Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder;
    5. @Bean
    6. public MappingJackson2HttpMessageConverter MappingJsonpHttpMessageConverter() {
    7. ObjectMapper mapper = jackson2ObjectMapperBuilder.build();
    8. // ObjectMapper为了保障线程安全性,里面的配置类都是一个不可变的对象
    9. // 所以这里的setDateFormat的内部原理其实是创建了一个新的配置类
    10. DateFormat dateFormat = mapper.getDateFormat();
    11. mapper.setDateFormat(new MyDateFormat(dateFormat));
    12. MappingJackson2HttpMessageConverter mappingJsonpHttpMessageConverter = new MappingJackson2HttpMessageConverter(
    13. mapper);
    14. return mappingJsonpHttpMessageConverter;
    15. }
    16. }
  • 配置了上述代码之后,问题成功解决。

3、为什么往spring容器中注入MappingJackson2HttpMessageConverter,springMvc就会用这个Converter呢?

  • 查看springboot的源代码如下:

    1. @Configuration
    2. class JacksonHttpMessageConvertersConfiguration {
    3. @Configuration
    4. @ConditionalOnClass(ObjectMapper.class)
    5. @ConditionalOnBean(ObjectMapper.class)
    6. @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, havingValue = "jackson", matchIfMissing = true)
    7. protected static class MappingJackson2HttpMessageConverterConfiguration {
    8. @Bean
    9. @ConditionalOnMissingBean(value = MappingJackson2HttpMessageConverter.class, ignoredType = {
    10. "org.springframework.hateoas.mvc.TypeConstrainedMappingJackson2HttpMessageConverter",
    11. "org.springframework.data.rest.webmvc.alps.AlpsJsonHttpMessageConverter" })
    12. public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(
    13. ObjectMapper objectMapper) {
    14. return new MappingJackson2HttpMessageConverter(objectMapper);
    15. }
    16. }
  • 默认配置为,当spring容器中没有MappingJackson2HttpMessageConverter这个实例的时候才会被创建

  • springboot的思想是约定优于配置,也就是说,springboot默认帮我们配好了spring mvc的Converter,如果我们没有自定义Converter的话,那么框架就会帮我们创建一个,如果我们有自定义的话,那么springboot就直接使用我们所注册的bean进行绑定

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号