【问题标题】:@JsonCreator not working for @RequestParams in Spring MVC@JsonCreator 不适用于 Spring MVC 中的 @RequestParams
【发布时间】: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


【解决方案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());
  }
}

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

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 2015-01-11
    • 2018-04-19
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    • 2017-07-15
    • 2018-05-22
    • 1970-01-01
    相关资源
    最近更新 更多