@JsonFormat时间格式化注解使用

您所在的位置:网站首页 日期格式化注解 @JsonFormat时间格式化注解使用

@JsonFormat时间格式化注解使用

#@JsonFormat时间格式化注解使用| 来源: 网络整理| 查看: 265

@JsonFormat注解是一个时间格式化注解,比如我们存储在mysql中的数据是date类型的,当我们读取出来封装在实体类中的时候,就会变成英文时间格式,而不是yyyy-MM-dd HH:mm:ss这样的中文时间,因此我们需要用到JsonFormat注解来格式化我们的时间。

JsonFormat注解是jackson包里面的一个注解,因此在使用的时候需要引入fasterxml maven的jar包,如下所示。

com.fasterxml.jackson.core jackson-databind 2.9.2

引入fasterxml maven jar包之后,就可以在实体类属性上面使用@JsonFormat注解了,要注意的是,它只会在类似@ResponseBody返回json数据的时候,才会返回格式化的yyyy-MM-dd HH:mm:ss时间,你直接使用System.out.println()输出的话,仍然是类似“Fri Dec 01 21:05:20 CST 2017”这样的时间样式。

package demo; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; public class Student { private int id; private String username; @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8") private Date createDate; //getter setter省略。。。 }

 

当我们这样@ResponseBody输出json数据的时候,@JsonFormat注解标识的date属性就会自动返回yyyy-MM-dd HH:mm:ss样式的时间了,例如。

@PostMapping("/api/getStudent") @ResponseBody public Map findStudentById(Long stuId){ Map resultMap = new HashMap(); Student stu = StudentService.findStudentById(stuId); resultMap.put("result",stu); return resultMap; }

 

喜欢这篇文章?欢迎打赏~~

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3