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

时间:2019-02-05 09:37:58

标签: java json spring-boot spring-mvc enums

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

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

1 个答案:

答案 0 :(得分:0)

这是@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());
  }
}

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