@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/