【发布时间】:2019-06-29 02:12:19
【问题描述】:
@JsonCreator 没有反序列化枚举类型的 @RequestParam
我正在开发一个 Spring 应用程序,其中控制器正在接收 Spring 绑定到包装器对象的请求参数列表。其中一个参数是枚举类型,我通过某个属性名称接收它。
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 绑定到 CustomerSearchCriteria.country,但它没有这样做。我用@RequestBody 尝试了类似的注释并且效果很好,所以我猜他的Spring 绑定忽略了@JsonCreator。
任何有用的提示将不胜感激。
【问题讨论】:
-
很抱歉造成混淆,当我将 Json 主体用作@RequestBody 时,它会正确映射,但是当我传递请求参数(如在提到的端点中)时,枚举未绑定到 CustomerSearchCriteria。尝试了国家和国家/地区名称
-
因为你想自己做,因为你需要使用 initbinder 注释并创建 registerCustomEditor ,扩展 PropertyEditorSupport 的自定义编辑器,然后将其转换并绑定 initbinder 方法所以结帐链接devglan.com/spring-boot/…
-
这正是我最终解决这个问题的方式,即通过注册自定义编辑器将 Country.Netherlands 转换为 Country.NL 并完全删除 JsonCreator。还是谢谢。
标签: java json spring-boot spring-mvc enums