簡體   English   中英

使用 jackson 在 spring 引導中反序列化不區分大小寫的 requestParam 枚舉

[英]Deserialize requestParam enum case insensitive in spring boot using jackson

我有以下 api

  @GetMapping(value = "/employees")
    public List<Employee> getEmployees(
        @RequestParam(value = "mode", required = false) final EmployeeMode mode) {
        //calling service from here
    }

我將 EmployeeMode 枚舉作為 requestParam。

public enum EmployeeMode {

    REGULAR,
    ALL,
    TEMPROARY
}

我想接受不區分大小寫的請求。 嘗試使用@JsonAlias@JsonCreatorobjectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS, true); spring.jackson.mapper.accept-case-insensitive-enums: true 沒有什么對我有用。

我正在使用 spring 啟動 2.5.5。

如何使用 requestParam 接受不區分大小寫的請求? 如果 requestParam 為空/null,則要將默認枚舉設置為 ALL。

您可以通過實施轉換器來處理它。

public class EmployeeModeConverter implements Converter<String, EmployeeMode> {
    @Override
    public EmployeeMode convert(String source) {
        switch (source.toUpperCase()) {
            case "REGULAR": return EmployeeMode.Regular;
            case "TEMPROARY": return EmployeeMode.TEMPROARY;
            default: return EmployeeMode.ALL;
        }        
    }
}

@Configuration
public class Config extends WebMvcConfigurationSupport {
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new EmployeeModeConverter());
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM