好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Feign 日期格式转换错误的问题

出现的场景

服务端通过springmvc写了一个对外的接口,返回一个json字符串,其中该json带有日期,格式为yyyy-MM-dd HH:mm:ss 客户端通过feign调用该http接口,指定返回值为一个Dto,Dto中日期的字段为Date类型 客户端调用该接口后抛异常了。

报错异常如下

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)

从异常信息中我们可以看出,是在AbstractJackson2HttpMessageConverter类中调用了readJavaType方法之后抛的异常

一步一步往下深入,我们找到了最关键的地方,在DeserializationContext类的_parseDate方法中

执行了df.parse(dateStr)之后抛异常了

?

1

2

3

4

5

6

7

8

9

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的源码

?

1

2

3

4

5

6

7

8

protected DateFormat getDateFormat(){   

    if (_dateFormat != null ) {       

         return _dateFormat;

     }

     DateFormat df = _config.getDateFormat();

     _dateFormat = df = (DateFormat) df.clone();   

     return df;

}

DateFormat又是从MapperConfig而来

我们再看下config.getDateFormat()的源码

?

1

2

3

public final DateFormat getDateFormat() {

     return _base.getDateFormat();

}

我们知道,SpringMvc就是通过AbstractJackson2HttpMessageConverter类来整合jackson的,该类维护jackson的ObjectMapper,而ObjectMapper又是通过MapperConfig来进行配置的

由此可见,本异常就是因为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类型的时间戳

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

?

1

2

#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如下

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

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)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

@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;

     }

}

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

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

查看springboot的源代码如下:

?

1

2

3

4

5

6

7

8

9

10

@Configurationclass 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/hpc_2015/article/details/97897660

查看更多关于Feign 日期格式转换错误的问题的详细内容...

  阅读:16次