Home > Software design >  Accept and parse integer for Enum type query parameter in Java
Accept and parse integer for Enum type query parameter in Java

Time:10-13

An API in my spring boot app has a query parameter of an Enum type. From the postman, it accepts only Enum string value. It responds with 400 for integer when sent as the query parameter value. How to configure for spring boot app to accept Enum string values or Enum index/ordinal values as query parameters.

below both the ways should work

  1. <base-url>/123/status?status=inprogress
  2. <base-url>/123/status?status=2 (2 is index of inprogress enum)

I am using Java, spring boot fw. It works well in dotNet

CodePudding user response:

As far as I know, there is no way to do this magically with an annotation or so. What you could do is implement a custom converter and convert the value inputted into your enum like this:

public class MyCustomEnumConverter implements Converter<String, YourEnum>
{
    @Override
    public YourEnum convert(String source) {
        try
        {
            if(isNumeric(source)) // If the string passed is a Number
            {
                int index = Integer.parseInt(source); 
                return YourEnum.values()[index]; // Get the Enum at the specific index
            }
            // Else if it is a string..
            return YourEnum.valueOf(source);
        } catch(Exception e) {
            return null; // or whatever you need
        }
    }

    private static boolean isNumeric(String str) {
        try {
            Integer.parseInt(str);
            return true;
        } catch(NumberFormatException e){
            return false;
        }
    }
}

And then register your Converter:

@Configuration
public class MyConfig extends WebMvcConfigurationSupport {
   @Override
   public FormattingConversionService mvcConversionService() {
       FormattingConversionService f = super.mvcConversionService();
       f.addConverter(new MyCustomEnumConverter());
       return f;
   }
}

You could improve the logic of MyCustomEnumConverter but for the sake of simplicity, I left it at that.

  • Related