zoukankan      html  css  js  c++  java
  • spring boot 如何映射json格式请求中的枚举值

    @RestController
    public class EmployeeController {
        @PostMapping("checkEmployee")
        public String checkEmployee(@RequestBody Employee employee) {
            return employee.getDepartment().getDepCode();
        }
    }

    请求实体:

    public class Employee {
     
        private String name;
     
        private DepartmentEnum department;
     
        public String getName() {
            return name;
        }
     
        public void setName(String name) {
            this.name = name;
        }
     
        public DepartmentEnum getDepartment() {
            return department;
        }
     
        public void setDepartment(DepartmentEnum department) {
            this.department = department;
        }
    }

    枚举:

    public enum Department {
     
        SALES("d1"),
     
        MARKETING("d2"),
     
        PRODUCTION("d3");
     
        private String depCode;
     
        private Department(String depCode) {
            this.depCode = depCode;
        }
     
        public String getDepCode() {
            return this.depCode;
        }
     
        /**
          * 增加映射方法,并为方法添加@JsonCreator
          */
        @JsonCreator
        public static Department getDepartmentFromCode(String value) {
            for (Department dep : Department.values()) {
                if (dep.getDepCode().equals(value)) {
                    return dep;
                }
            }
            return null;
        }
     
    }

    测试结果:

    参考:https://fullstackdeveloper.guru/2020/05/08/how-to-map-enum-types-to-json-requests-in-spring-boot-automatically/

  • 相关阅读:
    二叉排序树(B-Tree)-c实现
    队列(Queue)-c实现
    栈(stack)--c实现(使用双链表)
    链表(list)--c实现
    c 和 指针读书笔记(1)
    c traps and pitfalls reading notes(2)
    js 控制
    正则表达式
    Android 笔记
    Android 布局方式学习
  • 原文地址:https://www.cnblogs.com/joequa/p/13957052.html
Copyright © 2011-2022 走看看