@JsonCreator 不适用于 Spring MVC 中的 @RequestParams

Dev*_*Dev 7 java enums json spring-mvc spring-boot

@JsonCreator 不反序列化枚举类型的 @RequestParam

我正在开发一个 Spring 应用程序,其中控制器正在接收 Spring 绑定到包装器对象的请求参数列表。其中一个参数是 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;
    } 
}
Run Code Online (Sandbox Code Playgroud)

我期待 Spring 将枚举 Country.Netherlands 绑定到 CustomerSearchCriteria.country,但它没有这样做。我用@RequestBody 尝试了类似的注释,效果很好,所以我猜他 Spring 绑定忽略了 @JsonCreator。

任何有用的提示将不胜感激。

gaw*_*awi 1

这是@Mithat Konuk 评论背后的代码。

在你的控制器中放入如下内容:

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());
  }
}
Run Code Online (Sandbox Code Playgroud)

更多信息可以在这里找到:https://www.devglan.com/spring-boot/enums-as-request-parameters-in-spring-boot-rest