实体中的注解
@JsonFormat
tip:Spring Boot 内置了jackson来完成JSON的序列化和反序列化操作
<!--@JsonFormat依赖引入-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.7</version>
</dependency>
在实体类的属性上加注解@JsonFormat
, 其中参数:
pattern
:你想要其转换的日期格式
timezone
: 是时间设置为东八区,避免时间在转换中差8个钟
其实就是在java类序列化成json时控制字段的时间格式
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date studyDate;
举一个接口的例子:
@ApiOperation("json测试")
@GetMapping("/getDate")
public AjaxResult getDate() throws InterruptedException {
TExamInfo info = new TExamInfo();
info.setStartTime(new Date());
Thread.sleep(1000);
info.setOverTime(new Date());
return AjaxResult.success(info);
}
使用了 @JsonFormat
注解后,给前端的json:
{
"msg": "操作成功",
"code": 200,
"data": {
"startTime": "2021-03-26 15:29",
"overTime": "2021-03-26 15:29",
...
}
}
不加注释的话就会得到像这种格式(原始的格式):
{
"name": "张三",
"studyDate": "2020-06-08T06:26:19.335+0000"
}
@DateTimeFormat
@DateTimeFormat是Spring框架本身所有,所以对于Spring项目可以直接使用
如果注释注解@DateTimeFormat,前端传入String格式的时间后,服务器则会会报错500,原因是后端需要的是日期格式,但是前端给的是String。
Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'overTime';
所以需要加注解 @DateTimeFormat
来将前端传来的String 转为 Date类型
/** 考试开始时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm")
private Date startTime;
/** 考试结束时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm")
private Date overTime;
写个测试接口:
@ApiOperation("json测试")
@GetMapping("/setDate")
public AjaxResult setDate(TExamInfo info){
System.out.println("开始时间: " + info.getStartTime());
System.out.println("结束时间: " + info.getOverTime());
return AjaxResult.success(info);
}
我们在postman测试,可以看到后端可以正常接收到时间数据
![image.png](https://img-blog.csdnimg.cn/img_convert/175773b86ff5381fcd30916e64a419d3.png#align=left&display=inline&height=95&margin=[object Object]&name=image.png&originHeight=191&originWidth=1216&size=19292&status=done&style=shadow&width=607)
同时因为我们使用了 @JsonFormat
所以前端也能收到想要的格式
{
"msg": "操作成功",
"code": 200,
"data": {
"startTime": "2020-02-14 12:14",
"overTime": "2021-12-23 12:14",
}
}