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

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格式的字符串进行转换所导致的

 

问题处理

第一种处理方式:

时间属性添加注解,进行自动转换。

第二种方式:

异常说的值服务器返回了一个带有日期的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;
	}
}

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

 

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

查看springboot的源代码如下:

@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进行绑定

 

  • 7
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
YOLO高分设计资源源码,详情请查看资源内容中使用说明 YOLO高分设计资源源码,详情请查看资源内容中使用说明 YOLO高分设计资源源码,详情请查看资源内容中使用说明 YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明
当使用Feign进行远程调用时,如果服务端返回的结果中存在NaN(不是一个数字)类型的数据,Feign默认是无法将其正确转换的,会抛出转换错误的异常。 解决这个问题的方式是通过自定义Feign的解码器,在解码器中处理NaN类型的数据转换。下面是一个示例的自定义解码器的代码: ```java import feign.FeignException; import feign.Response; import feign.codec.Decoder; import feign.codec.ErrorDecoder; import org.springframework.beans.factory.ObjectFactory; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.cloud.openfeign.support.ResponseEntityDecoder; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import java.io.IOException; import java.lang.reflect.Type; public class CustomDecoder implements Decoder { private final ResponseEntityDecoder responseEntityDecoder; public CustomDecoder(ObjectFactory<HttpMessageConverters> messageConverters) { this.responseEntityDecoder = new ResponseEntityDecoder(new Decoder.Default(), messageConverters); } @Override public Object decode(Response response, Type type) throws IOException, FeignException { if (response.status() == HttpStatus.OK.value()) { ResponseEntity<?> entity = (ResponseEntity<?>) responseEntityDecoder.decode(response, type); Object body = entity.getBody(); // 处理NaN转换 if (body instanceof Double && ((Double) body).isNaN()) { return null; // 或者根据需求进行其他处理 } return body; } return responseEntityDecoder.decode(response, type); } } ``` 然后在FeignClient接口上添加`configuration`属性指定使用自定义解码器,例如: ```java @FeignClient(value = "your-service", configuration = CustomDecoder.class) public interface YourServiceClient { // ... } ``` 通过以上方式,你可以自定义处理Feign中NaN转换的问题。希望能帮到你!如果有更多问题,请继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值