Spring Boot和Feign中使用Java 8时间日期API(LocalDate等)的序列化问题

作者:媒体转发 时间:2018-06-17 01:04

字号

LocalDate、LocalTime、LocalDateTime是Java 8开始提供的时间日期API,主要用来优化Java 8以前对于时间日期的处理操作。然而,我们在使用Spring Boot或使用Spring Cloud Feign的时候,往往会发现使用请求参数或返回结果中有LocalDate、LocalTime、LocalDateTime的时候会发生各种问题。本文我们就来说说这种情况下出现的问题,以及如何解决。

Spring Boot和Feign中使用Java 8时间日期API(LocalDate等)的序列化问题

问题现象

先来看看症状。比如下面的例子:

@SpringBootApplication 

public class Application { 

 

    public static void main(String[] args) { 

        SpringApplication.run(Application.class, args); 

    } 

 

    @RestController 

    class HelloController { 

 

        @PostMapping("/user"

        public UserDto user(@RequestBody UserDto userDto) throws Exception { 

            return userDto; 

        } 

 

    } 

 

    @Data 

    @NoArgsConstructor 

    @AllArgsConstructor 

    static class UserDto { 

 

        private String userName; 

        private LocalDate birthday; 

 

    } 

 

上面的代码构建了一个简单的Spring Boot Web应用,它提供了一个提交用户信息的接口,用户信息中包含了LocalDate类型的数据。此时,如果我们使用Feign来调用这个接口的时候,会得到如下错误:

2018-03-13 09:22:58,445 WARN  [http-nio-9988-exec-3] org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Can not construct instance of java.time.LocalDate: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of java.time.LocalDate: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?) 

 at [Source: java.io.PushbackInputStream@67064c65; line: 1, column: 63] (through reference chain: java.util.ArrayList[0]->com.didispace.UserDto["birthday"]) 

分析解决

对于上面的错误信息JSON parse error: Can not construct instance of java.time.LocalDate: no suitable constructor found, can not deserialize from Object value,熟悉Spring MVC的童鞋应该马上就能定位错误与LocalDate的反序列化有关。但是,依然会有很多读者会被这段错误信息java.util.ArrayList[0]->com.didispace.UserDto["birthday"]所困惑。我们命名提交的UserDto["birthday"]是个LocalDate对象嘛,跟ArrayList列表对象有啥关系呢?

我们不妨通过postman等手工发一个请求看看服务端返回的是什么?比如你可以按下图发起一个请求:

责任编辑:CQITer新闻报料:400-888-8888   本站原创,未经授权不得转载
关键词 >>Spring Boot Java 8 API
继续阅读
热新闻
推荐
关于我们联系我们免责声明隐私政策 友情链接