REST parsing enum fails for string

117 views Asked by At

a REST URL is allowing access via a GET to an url which contains an enum value as a query parameter. If I send a request which contains the name of the enum variable it works but if I use a string value it doesn't.

Example: access via [...]cars/1?myEnum=CLIENT works but [...]cars/1?myEnum=Client doesn't. Why?

@XmlType
@XmlEnum
@RequiredArgsConstructor
public enum MyEnum {

    @XmlEnumValue("Client")
    CLIENT("Client"),
    @XmlEnumValue("Server")
    SERVER("Server");

    @Getter
    private final String value;

    public static MyEnum fromValue(String v) {
        for (MyEnum c : MyEnum.values()) {
            if (c.value.equals(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v);
    }
}

The client

@GET
@Path("cars/{myPathParam}")
@Produces(MediaType.TEXT_PLAIN)
public String getCars( //
        @PathParam("myPathParam") final String myPathParam,
        @QueryParam("myEnum") final MyEnum myEnum) {
    return "someValue";
}
1

There are 1 answers

0
Klave On BEST ANSWER

The problem was the name of the method. In my example above it is fromValue. However, according to the spec (JSR339, Chapter 3.2 Fields and Bean Properties) it should be valueOf or fromString:

Types that have a static method named valueOf or fromString with a single String argument that return an instance of the type. If both methods are present then valueOf MUST be used unless the type is an enum in which case fromString MUST be used.