常用注解@JsonField、@JsonFormat、@DateTimeFormat区别

2022年12月4日10:25:23

@JsonFormat

该注解来源于jackson包中的注解,主要用来控制后端返回给前端的日期格式,通常用在返回给前端的实体类中。
案例如下:

classUser{privateInteger id;@JsonFormat(pattern=”yyyy-MM-dd”,timezone=”GMT+8)privateDate birthday;}

注意:
如果直接使用 @JsonFormat(pattern=”yyyy-MM-dd”)就会出现2018-08-01 08:00:00的情况, 会相差8个小时,因为我们是东八区(北京时间)。所以我们在格式化的时候要指定时区(timezone )

@JsonField

该注解来源于阿里巴巴的fastjson,是阿里巴巴的开源框架,主要进行JSON解析和序列化。 @JsonField是集前端到后端、后端到前端数据传输于一身的注解
其中经常用到的参数有以下:
常用注解@JsonField、@JsonFormat、@DateTimeFormat区别
所以JsonField中format属性功能可以代替JsonFormat了。
更多关于@JsonField的用法可以查看我的另一篇博客博客,这里就不再讲解
fastjson使用方法

@DateTimeFormat

是spring自带的处理框架,主要用于将时间格式化。
在实体类上的注解使用,可以按格式处理前端传过来的日期

@DateTimeFormat(pattern=”yyyy-MM-dd”)privateDate date;

总结

@DateTimeFormat是前端数据到后端数据的处理
@JsonFormat是后端到前端数据的处理
@JsonField是集两者于一身的一个注解

综上所述,更建议使用@JsonField

  • 作者:sword to coding
  • 原文链接:https://blog.csdn.net/qq_56769991/article/details/126300846
    更新时间:2022年12月4日10:25:23 ,共 688 字。