当前位置: 首页 > news >正文

Java的@DateTimeFormat注解与@JsonFormat注解的使用对比

Java的@DateTimeFormat注解与@JsonFormat注解的使用对比

在Java开发中,处理日期和时间格式时,我们经常会使用到@DateTimeFormat@JsonFormat注解。这两个注解主要用于格式化日期和时间,但在使用场景和功能上有所不同。本文将详细介绍这两个注解的使用方法,并对比它们的异同点。

引入我的其他博客:
1、Java 前后端时间格式转换注解
https://blog.csdn.net/qq_29689343/article/details/125749447

文章目录

  • Java的@DateTimeFormat注解与@JsonFormat注解的使用对比
    • 一、简介
    • 二、使用场景
      • 1. @DateTimeFormat注解
      • 2. @JsonFormat注解
    • 三、基本使用
      • 1. @DateTimeFormat的基本使用
      • 2. @JsonFormat的基本使用
    • 四、功能详解
      • 1. @DateTimeFormat注解的功能
      • 2. @JsonFormat注解的功能
    • 五、最佳实践及案例
      • 1. 在Spring Boot项目中使用@DateTimeFormat和@JsonFormat
      • 2. 处理不同格式的日期
    • 六、总结

一、简介

在Spring和Jackson框架中,日期和时间格式化是一个常见需求。@DateTimeFormat注解主要用于Spring的表单绑定,而@JsonFormat注解则用于Jackson的JSON序列化和反序列化。了解这两个注解的使用场景和方法,可以帮助开发者更高效地处理日期和时间。

二、使用场景

1. @DateTimeFormat注解

@DateTimeFormat注解通常用于Spring MVC中,主要用于将字符串日期转换为Java的日期对象,或者将Java的日期对象转换为特定格式的字符串。

2. @JsonFormat注解

@JsonFormat注解主要用于Jackson库,通常在序列化和反序列化JSON数据时使用,用于指定日期和时间的格式。

三、基本使用

1. @DateTimeFormat的基本使用

在Spring MVC中,@DateTimeFormat注解可以用于控制器方法的参数:

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.time.LocalDate;@RestController
public class DateController {@GetMapping("/date")public String getDate(@RequestParam("date") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {return "Parsed date is: " + date.toString();}
}

2. @JsonFormat的基本使用

在使用Jackson进行JSON序列化和反序列化时,可以使用@JsonFormat注解来指定日期格式:

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;import java.time.LocalDate;public class User {@JsonFormat(pattern = "yyyy-MM-dd")private LocalDate birthDate;// getters and setterspublic static void main(String[] args) throws Exception {User user = new User();user.setBirthDate(LocalDate.of(1990, 1, 1));ObjectMapper mapper = new ObjectMapper();String json = mapper.writeValueAsString(user);System.out.println(json); // {"birthDate":"1990-01-01"}User deserializedUser = mapper.readValue(json, User.class);System.out.println(deserializedUser.getBirthDate()); // 1990-01-01}
}

四、功能详解

1. @DateTimeFormat注解的功能

  • 作用范围:主要用于Spring MVC的请求参数绑定和表单数据绑定。
  • 支持的类型:支持java.util.Datejava.time.LocalDatejava.time.LocalDateTime等。
  • 常用属性
    • pattern:指定日期格式模式,例如"yyyy-MM-dd"
    • iso:使用ISO标准格式,例如DateTimeFormat.ISO.DATE

2. @JsonFormat注解的功能

  • 作用范围:主要用于Jackson的JSON序列化和反序列化。
  • 支持的类型:支持java.util.Datejava.time.LocalDatejava.time.LocalDateTime等。
  • 常用属性
    • pattern:指定日期格式模式,例如"yyyy-MM-dd"
    • shape:指定数据的形状,例如JsonFormat.Shape.STRING
    • timezone:指定时区,例如"GMT+8"

五、最佳实践及案例

1. 在Spring Boot项目中使用@DateTimeFormat和@JsonFormat

在Spring Boot项目中,可以同时使用@DateTimeFormat@JsonFormat来处理不同场景下的日期格式化需求。

import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;import java.time.LocalDate;public class Event {@DateTimeFormat(pattern = "yyyy-MM-dd")@JsonFormat(pattern = "yyyy-MM-dd")private LocalDate eventDate;// getters and setters
}

2. 处理不同格式的日期

在不同的场景下,可能需要处理不同格式的日期。例如,在请求参数中使用@DateTimeFormat,在JSON序列化时使用@JsonFormat

import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.time.LocalDate;@RestController
public class EventController {@GetMapping("/event")public Event getEvent(@RequestParam("date") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {Event event = new Event();event.setEventDate(date);return event;}
}class Event {@JsonFormat(pattern = "MM/dd/yyyy")private LocalDate eventDate;// getters and setters
}

在这个例子中,请求参数使用yyyy-MM-dd格式,而返回的JSON数据使用MM/dd/yyyy格式。

六、总结

@DateTimeFormat@JsonFormat是处理日期和时间格式化的两个重要注解。@DateTimeFormat主要用于Spring MVC的请求参数绑定,而@JsonFormat主要用于Jackson的JSON序列化和反序列化。了解它们的使用场景和功能,可以帮助开发者更高效地处理日期和时间格式化需求。

通过本文的介绍,希望读者能够更清晰地理解@DateTimeFormat@JsonFormat的使用方法,并在实际项目中灵活应用。

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 微服务-MybatisPlus下
  • vue3双向绑定的原理
  • Sping项目只能勾选17和21 (已解决) 导致的后续Invalid bound statement (not found):
  • 壹佰全家桶全应用源码在线更新升级
  • Redis快速入门基础
  • springboot集成mybatis时,dao层的mapper类需要添加@Repository注解吗?
  • C++树形结构(3 树的中心、重心)
  • Keil5软件仿真error65报错解决
  • 【Vulnhub系列】Vulnhub_SecureCode1靶场渗透(原创)
  • AJAX之原理
  • Chiplet SPI User Guide 详细解读
  • C/C++:和为给定数(二分查找,快速排序)
  • Docker 安全及日志管理(包含SSL证书)
  • Robot Operating System——内部审查(Introspection)Service
  • html笔记
  • 【划重点】MySQL技术内幕:InnoDB存储引擎
  • Android框架之Volley
  • Golang-长连接-状态推送
  • JS基础篇--通过JS生成由字母与数字组合的随机字符串
  • k个最大的数及变种小结
  • python docx文档转html页面
  • react-core-image-upload 一款轻量级图片上传裁剪插件
  • Vue源码解析(二)Vue的双向绑定讲解及实现
  • 创建一种深思熟虑的文化
  • 融云开发漫谈:你是否了解Go语言并发编程的第一要义?
  • 突破自己的技术思维
  • 微信端页面使用-webkit-box和绝对定位时,元素上移的问题
  • 优化 Vue 项目编译文件大小
  • Hibernate主键生成策略及选择
  • 如何用纯 CSS 创作一个菱形 loader 动画
  • #if和#ifdef区别
  • (1)bark-ml
  • (11)工业界推荐系统-小红书推荐场景及内部实践【粗排三塔模型】
  • (2)nginx 安装、启停
  • (Arcgis)Python编程批量将HDF5文件转换为TIFF格式并应用地理转换和投影信息
  • (html5)在移动端input输入搜索项后 输入法下面为什么不想百度那样出现前往? 而我的出现的是换行...
  • (大众金融)SQL server面试题(1)-总销售量最少的3个型号的车及其总销售量
  • (二)fiber的基本认识
  • (附源码)springboot码头作业管理系统 毕业设计 341654
  • (论文阅读26/100)Weakly-supervised learning with convolutional neural networks
  • (使用vite搭建vue3项目(vite + vue3 + vue router + pinia + element plus))
  • (五)MySQL的备份及恢复
  • (原创)可支持最大高度的NestedScrollView
  • (转)一些感悟
  • (转载)(官方)UE4--图像编程----着色器开发
  • ***微信公众号支付+微信H5支付+微信扫码支付+小程序支付+APP微信支付解决方案总结...
  • **登录+JWT+异常处理+拦截器+ThreadLocal-开发思想与代码实现**
  • *setTimeout实现text输入在用户停顿时才调用事件!*
  • .“空心村”成因分析及解决对策122344
  • .net core 调用c dll_用C++生成一个简单的DLL文件VS2008
  • .Net Core 微服务之Consul(三)-KV存储分布式锁
  • .Net OpenCVSharp生成灰度图和二值图
  • .NET 将多个程序集合并成单一程序集的 4+3 种方法
  • .NET 线程 Thread 进程 Process、线程池 pool、Invoke、begininvoke、异步回调
  • .NET4.0并行计算技术基础(1)