当前位置: 首页 > 知识库问答 >
问题:

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

慎芷阳
2023-03-14

@JSONCreator未反序列化enum类型的@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;
    } 
}

我期待Spring将enum Country.Networds绑定到CustomerSearchCriteria.Country,但它没有这样做。我在@RequestBody中尝试了类似的注释,效果很好,所以我猜测Spring绑定忽略了@jsonCreator。

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

共有1个答案

璩慎之
2023-03-14

下面是@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。

 类似资料:
  • 我的GMAILIMAP代码在PHP从我的localhost工作得很好,但它不能从域工作。 我已完成以下项目: 1) 允许不太安全的应用登录2)在GMAIL帐户中启用IMAP 3)未启用双因素身份验证。4) 我也验证了帐户访问权限5)我还允许:http://www.google.com/accounts/DisplayUnlockCaptcha 可能是我在实时服务器上没有SSL的问题吗? 但我不断得

  • 问题内容: 嗨,我只是简单地尝试在www.example.com上获取h1标签,该标签显示为“ Example Domain”。该代码适用于http://www.example.com,但不适用于https://www.exmaple.com。我该如何解决这个问题?谢谢 问题答案: PhantomJSDriver不支持(所有)DesiredCapabilities。 你会需要: 记录在这里:htt

  • 所以我使用这种方法写入文件,它在windows上运行完全正常,但在mac上运行时,它会创建文件,但它们是空的。 我知道数据是正确的,因为它打印正确。感谢您的任何帮助,这真的让我绊倒了。

  • 我正在尝试将angular2应用程序与rails api连接起来。 为了使用rails身份验证,我希望能够在两个域之间共享cookies。当我在angular应用程序中调用http GET时,我会返回一个带有预期设置cookie字段的响应,当我发送下一个GET请求时,cookie也会随之发送。然而,当我将第二个GET替换为一个POST时,它不是。对于两个调用,我都使用withCredentials

  • 列名称的类型为int[] 上述查询适用于postgresql,但不适用于hsqldb,甚至适用于sql 尝试的hsqldb版本:2.2.9和2.3.0 在hsqldb中工作的sql是从table_name中选择x,unnest(column_name)y(x)x和y不是该表的列。

  • 我的selectOneMenu没有触发onchange事件。这是代码: selectOneMenu填充得很好,我可以选择不同的值。但我希望在更改选择后,页面会被刷新,即重新创建支持bean(RequestScoped)(onchange=“submit();”)?但是,当selectOneMenu中的选择被更改时,什么都不会发生。 此外,不调用值change listener PresetGrou