springBoot注解之@JsonFormat和@DateTimeFormat的作用

@DatetimeFormat

@DatetimeFormat是将String转换成Date,一般前台给后台传值时用

import org.springframework.format.annotation.DateTimeFormat;
/**
 * 前台传后台时, 字符串自动封装成日期
 */
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date startTime;    

@JsonFormat

@JsonFormat 将Date转换成String 一般后台传值给前台时

import com.fasterxml.jackson.annotation.JsonFormat;

/**
 * 后台返给前台时, 日期自动格式化
 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date endTime;

也可以同时使用在一个字段

	@ApiModelProperty(value = "创建时间")
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private Date createTime;

注意

  • @JsonFormat不仅可以完成后台到前台参数传递的类型转换,还可以实现前台到后台类型转换。
  • content-typeapplication/json时,优先使用@JsonFormatpattern进行类型转换。而不会使用@DateTimeFormat进行类型转换。
  • @JsonFormat注解的作用就是完成json字符串到java对象的转换工作,与参数传递的方向无关。

猜你喜欢

转载自blog.csdn.net/weixin_43825761/article/details/127286337
今日推荐