常常项目里转时间类型出现如下错误。
Can not deserialize value of type java.util.Date from String \"2018-10-24 12:12:12\" : not a valid representation (error: Failed to parse Date value '2018-10-24 12:12:12': Can not parse date \"2018-10-24 12:12:12Z\": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS'Z'', parsing fails (leniency? null))\n ...这种方式是最简单配置的,但是也限制了所有的接口,必须按照配置好的格式传入传出时间类型。当然,也有办法解决前端传入参数不匹配的问题,后边会说。
找到application.properties 文件,在其中加入下面这两行
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=GMT+8其中,yyyy-MM-dd HH:mm:ss 可以写为yyyy-MM-dd hh:mm:ss 。如果这种格式,表示传入传出参数必须要带有时分秒。如下的传入参数:
{ "countmj": "string", "creatdate": "2018-10-24 12:12:12" }其中接口部分post 请求的还可以如下写法:
@PostMapping("/posttwo") public Object getTest2(@RequestBody CqjyZcfxx zcfxx){ if(zcfxx == null){ return addResultMapMsg(false,"参数为空"); } zcfxx.setCreatdate(new Date()); return addResultMapMsg(true,zcfxx); }另外get 请求的写法如下:
@GetMapping("/gettwo") public Object getTest2(CqjyZcfxx zcfxx){ if(zcfxx == null){ return addResultMapMsg(false,"参数为空"); } zcfxx.setCreatdate(new Date()); return addResultMapMsg(true,zcfxx); }但是,千万别如下这种写法,get 请求不支持@RequestBody 的。
@GetMapping("/getone") public Object getTest1(@RequestBody CqjyZcfxx zcfxx){ if(zcfxx == null){ return addResultMapMsg(false,"参数为空"); } System.out.println(zcfxx.getCreatdate()); return addResultMapMsg(true,zcfxx); }当然我们可能还有这样的问题,不同的前端人员,可能用不同的格式对你的小date传入,比如是时间戳丢给你,date表达式丢给你,明明你是年月日时分秒,他非要给你个年月日,等等。那改怎么办呢? 如果出现了这种情况,也好办,只不过需要变一下接收办法即可。方法有两种:
ObjectMapper 这个不需要引包,只需要在controller 里这么写:
@RequestMapping(value="/add",method = RequestMethod.POST) public Object addUser(@RequestBody String req){ ObjectMapper jsonTranster = new ObjectMapper().setDateFormat(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")); CqjyXmtp cqjyXmtp = null; try{ cqjyXmtp = jsonTranster.readValue(req, CqjyXmtp.class); }catch (Exception e) { e.printStackTrace(); return false; }还有一种,是以Gson 的方式转json串,这个需要引入包,我引的是下边的依赖:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.0</version> </dependency>写法差不多:
@RequestMapping(value="/add",method = RequestMethod.POST) public Object addUser(@RequestBody String req){ Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd hh:mm:ss").create(); CqjyXmtp cqjyXmtp = null; try{ cqjyXmtp = gson.fromJson(req,CqjyXmtp .class); }catch (Exception e) { e.printStackTrace(); return false; }如果没什么特殊要求,我觉得,用第一种最好!