文档章节

自定义jackson解析时间格式yyy-MM-dd HH:mm:ss

落叶清风
 落叶清风
发布于 08/08 19:00
字数 1974
阅读 190
收藏 3

1、问题排查

  1. 出现的场景:

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

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

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

  2. 异常如下:

    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)之后抛异常了

    • 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()的源码

    • 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类型的时间戳

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

  • #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;
    	}
    }
    

     

  • 配置了上述代码之后,问题成功解决。

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

  • 查看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

 

© 著作权归作者所有

共有 人打赏支持
落叶清风
粉丝 9
博文 42
码字总数 21216
作品 0
杭州
后端工程师
Log4j扩展使用--日志格式化器Layout

Layout:格式化输出日志信息 #自定义样式 #%c 输出所属的类目,通常就是所在类的全名 #%C 输出Logger所在类的名称,通常就是所在类的全名 #%d 输出日志时间点的日期或时间,默认格式为ISO86...

courtzjl
01/31
1
0
json字符串中包含多个日期时间格式 jackson 如何解析成pojo

比如说 String str1="{'moduleCode':'0001','moduleName':'aaaaa','openDate':'2015-12-22','endDate':'2015-12-22 10:10:10','moduleParent':100},"; json字符串 时间类型的格式有yyyy-MM-d......

木瞳2016
2015/12/22
4.8K
2
Log4j的ConversionPattern参数的格式含义

Log4j建议只使用四个级别,优先级从高到低分别是ERROR、WARN、INFO、DEBUG #这里定义能显示到的最低级别,若定义到INFO级别,则看不到DEBUG级别的信息了~! log4j.rootLogger=DEBUG #将DAO层log...

虾米团长
2011/06/04
0
0
Oracle数据库的时间格式和Jave时间格式区别总结

一、Oracle时间格式的SQL语句 --12小时制系统当前时间(上午) SQL>select tochar(sysdate,'YYYY-MM-DD HH12:MI:SS AM')from dual; --24小时制系统当前时间(下午) SQL> select tochar(sys...

Abel-ymg
2013/08/08
567
0
Mybatis 使用@requestbody 日期自定义转换

通常情况下,使用@requestbody json这种传参格式的时候 日期转换可能会遇到的问题。 查看源码 /** * Defines a commonly used date format that conforms * to ISO-8601 date formatting st...

JTA的阿呆
2016/07/21
94
0

没有更多内容

加载失败,请刷新页面

加载更多

LSM-Tree 大数据索引技术

一、LSM-Tree概述 核心思想就是放弃部分读能力,换取写入能力的最大化。LSM-Tree ,这个概念就是结构化合并树(Log-Structured Merge Tree)的意思,它的核心思路其实非常简单,就是假定内存...

PeakFang-BOK
17分钟前
0
0
vue.js响应式原理解析与实现

从很久之前就已经接触过了angularjs了,当时就已经了解到,angularjs是通过脏检查来实现数据监测以及页面更新渲染。之后,再接触了vue.js,当时也一度很好奇vue.js是如何监测数据更新并且重新...

peakedness丶
23分钟前
0
0
Weblogic补丁升级操作步骤

linux平台: weblogic1036 1:停止weblogic服务 2:打FMJJ补丁 a:获取weblogic_home目录并执行命令:export weblogic_home="/weblogic/wls1036_x64",(此目录一般为目录“user_projects”上...

fang_faye
36分钟前
0
0
04-《Apache Tomcat 9 User Guide》之部署项目

1.Introduction Deployment is the term used for the process of installing a web application (either a 3rd party WAR or your own custom web application) into the Tomcat server. 部......

飞鱼说编程
36分钟前
0
0
一位十年的老码农他眼中的区块链

大家可能已经听说过比特币、莱特币、以太币等等,以及它们作为一种新货币在市场上的潜力。 有趣的是,很多投资比特币的人也提到了区块链之类的东西。 显然,这项技术是比特币等其他东西的"基...

小刀爱编程
44分钟前
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部