@JsonFormat、@DateTimeFormat、@JsonSerialize注解的使用


@JsonFormat

是jackson的注解,用于后台返回前台的时候将后台的date类型数据转为string类型格式化显示在前台,加在get方法或者date属性上面,因为 @JsonFormat 注解不是 Spring 自带的注解,所以使用该注解前需要添加 jackson 相关的依赖包。当然,如果是 SpringBoot 项目就不需要自己手动添加依赖了,因为在 spring-boot-start-web 下已经包含了 jackson 相关依赖。

示例: @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") 

@DateTimeFormat

是spring的注解,用于前台将数据传到后台的时候将string类型数据转为date类型格式化插入到数据库中

示例: @DateTimeFormat(pattern = "yyyy-MM-dd") 

@JsonSerialize

也是jackson的注解,与@JsonFormat类似,但是功能更丰富,支持自定义

使用:

1.首先自定义日期序列化类

public class JsonDateSerializer extends JsonSerializer {

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override

    public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)

            throws IOException, JsonProcessingException {

        String value = "";

        if (null != date) {

            value = dateFormat.format(date);

        }

        gen.writeString(value);

    }

}

2.在实体的get方法或date属性上加上@JsonSerialize(using = JsonDateSerializer.class)即可