客户端通过SpringCloud调用服务端,服务端返回值包含da

2018-07-05  本文已影响0人  初晨的笔记

1、问题排查

出现的场景:

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

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

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

报错异常如下:

10:38:50 [ERROR]   >> com.syt.firefly.cloud.service.cms.CmsManageController:35
feign.codec.DecodeException: JSON parse error: Can not deserialize value of type java.util.Date from String "2018-07-04 13:32:50": not a valid representation (error: Failed to parse Date value '2018-07-04 13:32:50': Can not parse date "2018-07-04 13:32:50": while it seems to fit format 'yy
yy-MM-dd'T'HH:mm:ss.SSS', 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-07-04 13:32:50": not a valid representation (error: Failed to parse Date value '2018-
07-04 13:32:50': Can not parse date "2018-07-04 13:32:50": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS', parsing fails (leniency? nul
l))
 at [Source: java.io.PushbackInputStream@6fdf3c74; line: 1, column: 654] (through reference chain: java.util.ArrayList[0]->com.syt.firefly.cloud.
service.cms.bean.ClassicCaseVo["created"])
    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.$Proxy146.getList(Unknown Source)
    at com.syt.firefly.cloud.service.cms.CmsManageController.getList(CmsManageController.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
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()));
    }
}

protected DateFormat getDateFormat()
{
    if (_dateFormat != null) {
        return _dateFormat;
    }
    DateFormat df = _config.getDateFormat();
    _dateFormat = df = (DateFormat) df.clone();
    return df;
}

public final DateFormat getDateFormat() { return _base.getDateFormat(); }

2、问题处理

#spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
#spring.jackson.time-zone=Asia/Chongqing
 
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);
    }
}

@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呢?

@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 Mvc使用Jackson进行json转对象时,遇到的字符串转日期的异常处理(Can not deserialize value of type Date from String) ,刚刚在调用过程发现这个问题,遂记录一下,谢谢原作者。

上一篇 下一篇

猜你喜欢

热点阅读