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

标签 java json spring-boot spring-mvc enums

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

相关文章:

java - Spring 尝试反序列化为 LinkedHashMap 而不是 POJO

使用 MediaRecorder#stop 时出现 java.lang.RuntimeException : stop failed.

java - Android 适配器传递 JSON 对象数据?

JSON 模式 - 如何使用 oneOf

python - 需要帮助调试由 "Internal server error"引起的 heroku 应用程序上的 "JSON serializable"

java - Spring boot JPA Postgres enrity 未保存

java - Spring Boot Security XML 与 CSRF 的 WebSecurityConfigurerAdapter

java - Java数据结构的空间复杂度

java - Android 发送电子邮件,附件错误

java - 如何在spring mvc Controller 中读取具有多个数组的json?