@DateTimeFormat 注解 和 @JsonFormat 注解

2022年12月5日08:26:47

一、背景

 平常在web开发过程中,在前后台日期数据的交互过程中,经常会遇到一些问题。实体类里面使用的是java.util.Date类型保存日期数据。而前台向后台传递数据的时候用的是字符串。这样会出现格式转换问题。而在后台向前台传递数据的过程中。日期格式将会被转换为长整型。这显然不是我们想要的结果。为了解决此类问题。就用到了@DateTimeFormat注解  和@JsonFormat 注解。

二、发现问题

在网上查阅资料的过程中,发现大部分作者给出的解释并不全面,大多数都是说,前台向后台传递数据用@DateTimeFormat注解。而后台向前台传递就用@JsonFormat注解。。实际上@DateTimeFormat注解只会在类似@RequestParam的请求参数(url拼接的参数才生效,如果是放到RequestBody中的form-data也是无效的)上生效,如果@DateTimeFormat放到@RequestBody下是无效的。而@JsonFormat注解却可以转换这种情况下的参数。

三、对比总结及使用

     1. @DateTimeFormat用于前台向后台 ,将传入的字符串转换为Date类型。当然只能转换类似于@RequestParam()这种url拼接的参数。

        ①引入依赖(spring就不写了)

<!-- joda-time -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.3</version>
</dependency>

       ② 在实体类的需要类型转换的属性上加上@DateTimeFormat注解。

package com.**.model;

import lombok.Data;

@Data
public class User {
    private Integer id;
    private String userName;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date birth;
}

   2. @JsonFormat 后台向前台,将日期格式的数据格式转化为们所需要的数据。

                               前台向后台,将 Content-Type类型为application/json的字符串转换为Date类型。u

      ①. 引入依赖(spring boot项目已经帮我们引入了,所以不需要重复引入)

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.8</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.8</version>
</dependency>

<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>

     ② 在实体类的需要类型转换的属性上加上@JsonFormat注解。

package com.**.model;

import lombok.Data;

@Data
public class User {
    private Integer id;
    private String userName;
    @JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8")
    private Date birth;
}

3.参数解释

@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
pattern :需要转换的日期格式
timezone:时区,北京时间东八区 所以是GMT+8

四、总结

    1.后台向前台的日期类型格式化。只需要@JsonFormat一个注解就可以了

    2.前台向后台则需要 需求分析到底使用@JsonFormat注解 还是 @DateTimeFormat注解。

原文链接:http://www.jhone.top

  • 作者:残城碎梦
  • 原文链接:https://blog.csdn.net/weixin_42232296/article/details/108762967
    更新时间:2022年12月5日08:26:47 ,共 1873 字。