@JsonFormat时间格式化注解使用

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

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

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.2</version>
</dependency>

引入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<String,Object> findStudentById(Long stuId){
    Map<String,Object> resultMap = new HashMap<>();
    Student stu = StudentService.findStudentById(stuId);
    resultMap.put("result",stu);
    return resultMap;
}

 

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

 

posted @ 2018-12-07 16:32  苍青浪  阅读(85363)  评论(1编辑  收藏  举报