0

I'm having below api

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

I'm having EmployeeMode enum as requestParam.

public enum EmployeeMode {

    REGULAR,
    ALL,
    TEMPROARY
}

I want to accept request with case insensitive. Tried with @JsonAlias, @JsonCreator and objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS, true); and spring.jackson.mapper.accept-case-insensitive-enums: true. nothing worked for me.

I'm using spring boot 2.5.5.

How to accept case insensitive request with requestParam? And if requestParam is empty/null, want to set default enum as ALL.

Remo
  • 534
  • 7
  • 26
  • *And if requestParam is empty/null, want to set default enum as ALL.* I think, that can you only manage with a custom deserializer – Jens Jan 09 '23 at 06:42
  • Which library do you use to deserialize the requests? `jackson` or `gson`? – Jens Jan 09 '23 at 06:43
  • using jackson. and for setting default @RequestParam(value = "mode", required = false, defaultValue = "ALL"), this will help – Remo Jan 09 '23 at 06:45
  • This is a regular `@RequestParam` that doesn't use the json serialization but rather plain request parameter binding. So you would need a custom converter for that, a `String` to `EmployeeMode` converter. For the default you could set `ALL` as the default value (you can then remove `required=false` as that is then implied). – M. Deinum Jan 09 '23 at 06:45
  • Have you read [this](https://stackoverflow.com/questions/24157817/jackson-databind-enum-case-insensitive) – Jens Jan 09 '23 at 06:46
  • @Jens I read that and tried. but not worked out for me – Remo Jan 09 '23 at 06:47
  • @Jens he is binding a regular parameter not deserializing a JSON body, so trying to solve this with configuring JSON (de)serializers or Jackson or Gson won't help a bit as that isn't being used at all when binding request parameters. – M. Deinum Jan 09 '23 at 06:59

1 Answers1

3

You can handle it by implementing converter.

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());
    }
}
bidulgi69
  • 51
  • 2
  • Careful with the WebMvcConfigurationSupport, it can have [huge consequences](https://stackoverflow.com/q/17898606/1651107), better to use WebMvcConfigurer that has same addFormatters method – Piro Apr 04 '23 at 12:02