In Spring Boot 2.5, how do I convert an enum with a String value to my @RequestParam?

270 Views Asked by At

I'm using Spring Boot 2.5. I have this enum

public enum MyEnum {
    VALUE1("Label 1"),
    VALUE2("Label 2"),
    VALUE3("Label 3");

    private String label;

    MyEnum(String label) {
        this.label = label;
    }

    public String getLabel() {
        return label;
    }
}

and this controller method that I want to accept the enum

...
@RestController
public class MyController {

    @GetMapping("/my-endpoint")
    public String myEndpoint(@RequestParam MyEnum myEnum) {
        // Your code here
        return "Received enum value: " + myEnum + " with label: " + myEnum.getLabel();
    }
}

The problem is when I submit a request like "/my-endpoint?myEnum=label%201", I get the error, "Failed to convert value of type 'java.lang.String' to required type". What else do I need to do to allow conversion to happen successfully?

0

There are 0 best solutions below