解决spring boot接收前端传递过来的json数据时,接收到的时间与实际传递时间不一致的问题

来源:互联网 发布:长沙网络自考 编辑:程序博客网 时间:2024/05/01 17:32

spring boot接收前端传递过来的时间,总是比实际时间晚几个小时或者早几个小时,这是由于使用在@RequestBody 实体类,进行接收json类型字符串的时候,会把接受的string时间字段转换成lang类型,然后对应实体类的时候,会按照GMT+0时区的时间进行处理。

解决办法:
1,使用@JsonFormat注解,并且指定时区

@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")private Date timingDate;

2,使用@DateTimeFormat注解,但此方法在pattern="yyyy-MM-dd HH:mm:ss"时不适用Jackson,只支持时间类型为pattern="yyyy-MM-dd"的。

@DateTimeFormat(pattern="yyyy-MM-dd")private Date timingDate;

3,Controller接收时,按照json字符串接收,然后代码对应到bean里时,特殊处理时间字段。

需要使用到net.sf.json。

import net.sf.json.JSONObject;

import net.sf.json.util.JSONUtils;

@RequestMapping("/insideByJson.tml")public @ResponseBody Map<String, Object> insideByJson(@RequestBody String jsonParam) {//json字符串转换成beanJSONObject json=JSONObject.fromObject(jsonParam);String[] dateFormats = new String[]{"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd"};          JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(dateFormats));        Inside inside=(Inside) JSONObject.toBean(json, Inside.class);}



阅读全文
0 0