繁体   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