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;
    }
 
}

测试结果:

spring boot 如何映射json格式请求中的枚举值

上一篇:SQLAlchemy 多对多


下一篇:实施工程师面试题(答案)