SpringBoot笔记 --- @JsonFormat和@DateTimeFormat的作用

拥有回忆 提交于 2019-12-06 13:50:38

@DatetimeFormat

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

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

@JsonFormat

@JsonFormat(pattern=”yyyy-MM-dd”) 将Date转换成String 一般后台传值给前台时

import com.fasterxml.jackson.annotation.JsonFormat;

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

注意

@JsonFormat不仅可以完成后台到前台参数传递的类型转换,还可以实现前台到后台类型转换。

当content-type为application/json时,优先使用@JsonFormat的pattern进行类型转换。而不会使用@DateTimeFormat进行类型转换。

@JsonFormat注解的作用就是完成json字符串到java对象的转换工作,与参数传递的方向无关。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!