关于@JsonFormat和@DateFormat问题

今天在调试web应用的时候,碰到时间序列化和反序列化问题,网上查的资料一般都是关于 @JsonFormat @DateFormat

网上好多说的是 @JsonFormat 是 把 对象转 string 即序列化起作用,@DateFormat 是string 转 对象 即反序列化起作用,也有的说 @JsonFormat 序列化和反序列化都有作用。

其实问题不是这个简单,到底谁起作用是有条件的。

1、当前端请求 content-Type application/json

  请求到后端 string 转 对象 是 @JsonFormat 起作用。

domain文件

controller层

postman发请求。

从上面可以看出,后端反序列化出错

现在我把注解换下,如下

public class Test {

    @JsonFormat(pattern = "yyyy-MM-dd")
//    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date date1;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
//    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date date2;

    public Date getDate1() {
        return date1;
    }

    public void setDate1(Date date1) {
        this.date1 = date1;
    }

    public Date getDate2() {
        return date2;
    }

    public void setDate2(Date date2) {
        this.date2 = date2;
    }

}

此时后端能调通,且返回的结果时间格式是正确的,我们可以发现这种情况下@JsonFormat在反序列化和序列化过程都起作用了。

2、当请求类型:content-Typeform-data

此时domain还和上面一样,请求url换func1,因为

猜你喜欢

转载自www.cnblogs.com/lqwh/p/11229031.html