问题形容

Spring Cloud通过Feign客户端调用HTTP接口,如果返回值中蕴含LocalDateTime类型(包含其余JSR-310中java.time包的工夫类),在客户端可能会呈现反序列化失败的谬误。错误信息如下:

feign.codec.DecodeException: Type definition error: [simple type, class java.time.LocalDateTime]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.LocalDateTime` (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2019-11-27T11:04:32')Caused by: org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class java.time.LocalDateTime]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.LocalDateTime` (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2019-11-27T11:04:32')Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.LocalDateTime` (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2019-11-27T11:04:32')

问题剖析

搜寻到一个相似问题:http://blog.didispace.com/Spring-Boot-And-Feign-Use-localdate/,然而文中提供的办法并不能解决问题。
经试验,Spring Cloud的HTTP接口间接调用的参数或返回值中的LocalDateTime类型是能够失常序列化和反序列化的,然而通过Feign客户端调用,反序列化时就可能产生谬误。
跟踪代码发现Feign客户端反序列化通过feign.codec.Decoder接口的实现类SpringDecoder最终调用org.springframework.http.converter.json.MappingJackson2HttpMessageConverter,这是默认的Spring MVC应用的HttpMessageConverter,所以雷同的转换器在不同的调用形式下产生了不一样的后果依然不得而知。

问题解决

减少依赖

<dependency>    <groupId>com.fasterxml.jackson.datatype</groupId>    <artifactId>jackson-datatype-jsr310</artifactId>    <version>2.9.9</version></dependency>

字段减少注解

POJO类的LocalDateTime类型字段减少如下注解

@JsonDeserialize(using = LocalDateTimeDeserializer.class)private LocalDateTime createTime;