@JsonCreator 不反序列化枚举类型的 @RequestParam
我正在开发一个 Spring 应用程序,其中 Controller 正在接收 Spring 绑定(bind)到包装器对象的请求参数列表。其中一个参数是 enum 类型,我通过某个属性名称接收它。
Endpoint example: http://localhost:8080/searchCustomers?lastName=Smith&country=Netherlands
@RequestMapping(value = "/search/customers", method = RequestMethod.GET)
public CustomerList searchCustomers(@Valid CustomerSearchCriteria searchCriteria)
public class CustomerSearchCriteria {
private String lastName;
private Country country;
}
public enum Country {
GB("United Kingdom"),
NL("Netherlands")
private String countryName;
Country(String countryName) {
countryName = countryName;
}
@JsonCreator
public static Country fromCountryName(String countryName) {
for(Country country : Country.values()) {
if(country.getCountryName().equalsIgnoreCase(countryName)) {
return country;
}
}
return null;
}
@JsonValue
public String toCountryName() {
return countryName;
}
}
我期待 Spring 将枚举 Country.Netherlands 绑定(bind)到 CustomerSearchCriteria.country,但它没有这样做。我用@RequestBody 尝试了类似的注释,效果很好,所以我猜他 Spring 绑定(bind)忽略了 @JsonCreator。
任何有用的提示将不胜感激。
最佳答案
这是@Mithat Konuk 评论背后的代码。
放入您的 Controller ,例如:
import java.beans.PropertyEditorSupport;
@RestController
public class CountryController {
// your controller methods
// ...
public class CountryConverter extends PropertyEditorSupport {
public void setAsText(final String text) throws IllegalArgumentException {
setValue(Country.fromCountryName(text));
}
}
@InitBinder
public void initBinder(final WebDataBinder webdataBinder) {
webdataBinder.registerCustomEditor(Country.class, new CountryConverter());
}
}
更多信息可以在这里找到:https://www.devglan.com/spring-boot/enums-as-request-parameters-in-spring-boot-rest .
关于java - @JsonCreator 不适用于 Spring MVC 中的 @RequestParams,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54531359/