自定义 feign 反序列化时间字符格式

参考 :
https://blog.csdn.net/forezp/article/details/73480304

feign client 默认配置类:默认的配置类为FeignClientsConfiguration 配置了解码和编码。

当请求Feign Client的方法执行时会被 SynchronousMethodHandler 类中的 invoke 方法所拦截。

跟踪代码可知, feign 反序列化对象时,使用 jackson

objectMapper 类在 com.fasterxml.jackson.databind 包中

解析时间格式

重写 DateFormat,从而支持 yyy-MM-dd HH:mm:ss 的字符串格式时间能转化为 Date 对象,而默认格式时间格式支持:2018-07-04T06:23:15.338Z

@Slf4j
public class CustomJackDateFormat extends DateFormat {
    private SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
    private DateFormat dateFormat;

    public CustomJackDateFormat(DateFormat dateFormat) {
        this.dateFormat = dateFormat;
        // 时间转换时,默认相差 8 小时,所以这里设置了时区
        dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        log.info("自定义 jackson时间 转化格式初始化");
    }


    @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 = format.parse(source, pos);
        } catch (Exception e) {
            // 不行,那就按原先的规则吧
            date = dateFormat.parse(source, pos);
        }
        return date;
    }

    // 这里装饰clone方法的原因是因为clone方法在jackson中也有用到
    @Override
    public Object clone() {
        Object format = dateFormat.clone();
        return new CustomJackDateFormat((DateFormat) format);
    }
}

重新设置 ObjectMapper 的时间格式

@Configuration
@Slf4j
public class CustomWebConfig {


    @Autowired(required = false)
    private Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder;


    @Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        ObjectMapper mapper = jackson2ObjectMapperBuilder.build();
        // ObjectMapper为了保障线程安全性,里面的配置类都是一个不可变的对象
        // 所以这里的setDateFormat的内部原理其实是创建了一个新的配置类
        DateFormat dateFormat = mapper.getDateFormat();
        // 自定义 jackson 转换时间格式
        mapper.setDateFormat(new CustomJackDateFormat(dateFormat));

        MappingJackson2HttpMessageConverter mappingJsonpHttpMessageConverter = new MappingJackson2HttpMessageConverter(
                mapper);
        return mappingJsonpHttpMessageConverter;
    }
}

猜你喜欢

转载自www.cnblogs.com/zhangjianbin/p/9298968.html