@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<Date> { 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)即可
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】开源 Linux 服务器运维管理面板 1Panel V2 版本正式发布
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步