问题一:
后台在返回json格式的Date类型数据时,直接通过@ResponseBody返回出去的是一个长整型时间戳:
解决方法:
@JsonFormat(pattern = “yyyy-MM-dd HH:mm:ss”,timezone = “GMT+8”)
它的作用是,出参时,自动把Date型对象数据转化成格式化后的字符串输出: yyyy-MM-dd HH:mm:ss
案例:
- timezone是用于调整时区的属性(东八区),不加的话得到的时间会比实际的少8个小时
Postman请求结果:

问题二:
前端以字符串的形式给后台传递 带有格式的 日期 和 数字 数据,导致后台无法解析数据:

解决方法:
总结:
1.如果前后端传的数据都是json格式,那么后台接数据,传数据都可以用@JsonFormat ;
2.@DateTimeFormat适合后端接收前端传来的数据,不管是不是json格式都可以正确转换成Date型数据,只要前端传来的格式正确且后端@DateTimeFormat的pattern写正确。但是,这个注解无法将Date型数据用json传到前端去
解决spring boot接收前端传递过来的json数据时,接收到的时间与实际传递时间不一致的问题
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字符串转换成bean
JSONObject 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);
}