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/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM