• @DateTimeFormat和@JsonFormat


    参考:Jackson(2)之@JsonFormat和@DateTimeFormat本质区别

    Person

    @Data
    public class Person {
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private Date birth;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    Test1Controller

    @RestController
    public class Test1Controller {
    
        @GetMapping("test01")
        // 如果这里不加@DateTimeFormat, 将不能把字符串转为日期
        // 访问:localhost:8083/test01?date=2020-01-01 10:10:11
        // 也可以使用form-data传参
        // (get请求不能使用x-www-form-urlencoded)
        public Object test01(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date date) {
            System.out.println(date);
            return date;
        }
    
        // 如果Person#birth不加@DateTimeFormat, 将不能把字符串转为日期
        // 访问:localhost:8083/test02?birth=2020-01-01 10:10:11
        // 也可以使用form-data传参
        // (get请求不能使用x-www-form-urlencoded)
        @GetMapping("test02")
        public Object test02(Person p) {
            System.out.println(p);
            return p;
        }
    
        // 如果不加@DateTimeFormat, 将不能把字符串转为日期
        // 访问:localhost:8083/test03?date=2020-01-01 10:10:11
        // 也可以使用form-data传参
        // 也可以使用x-www-form-urlencoded带参数
        @PostMapping("test03")
        public Object test03(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date date) {
            System.out.println(date);
            return date;
        }
    
        // 如果Person#birth不加@DateTimeFormat, 将不能把字符串转为日期
        // 访问:localhost:8083/test03?date=2020-01-01 10:10:11
        // 也可以使用form-data传参
        // 也可以使用x-www-form-urlencoded带参数
        @PostMapping("test04")
        public Object test04(Person p) {
            System.out.println(p);
            return p;
        }
    
        // 不能使用@DateTimeFormat(SpringMvc注解), 而要使用@JsonFormat(Jackson注解),否则不能解析
        // (之前错误的认为@DateTimeFormat是解析日期用的,@JsonFormat是格式化日期用的)
        // 并且只能使用json格式传参
        @PostMapping("test05")
        public Object test05(@RequestBody Person p) {
            System.out.println(p);
            return p;
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
  • 相关阅读:
    【校招VIP】java语言类和对象之map、set集合
    油猴脚本:bing 搜索结果居中
    C语言之qsort()函数的模拟实现
    一文带你了解”数据分箱“技术
    深度学习资源列表
    php文件操作
    C语言基础之负数是怎么存储的?(六十一)
    软件测试就业现状分析,2023是卷还是润?
    JUC学习笔记——共享模型之内存
    【Flink源码】再谈Flink程序提交流程(中)
  • 原文地址:https://blog.csdn.net/qq_16992475/article/details/127869313