2

I am having problems making RestEasy (3.0.10.Final) parse a path parameter into an enum value.

Having the enum definition...

package com.stines;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonValue;

public enum MyNumber {
    One("number-one"), Two("number-two");

    @JsonIgnore private final String text;

    @JsonIgnore
    private MyNumber(final String text) {
        this.text = text;
    }

    @JsonValue
    public String getText() {
        return text;
    }

    @JsonCreator
    public static MyNumber byText(final String text) {
        for (final MyNumber value : MyNumber.values()) {
            if (value.getText().equals(text)) return value;
        }
        throw new IllegalArgumentException("Unknown number");
    }
}

... and the endpoint...

@PUT
@Path("{number}")
void putNumber(
        @PathParam("number") MyNumber number
);

... I would expect to be able to hit PUT http://my-server/number-one.

I see the following though:

Caused by: java.lang.IllegalArgumentException: No enum constant com.stines.MyNumber.number-one
    at java.lang.Enum.valueOf(Enum.java:238)
    at com.stines.MyNumber.valueOf(MyNumber.java:7)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.jboss.resteasy.core.StringParameterInjector.extractValue(StringParameterInjector.java:343)
    ... 34 more

What am I missing here?? Thanks a lot.

Stine
  • 1,605
  • 5
  • 23
  • 44
  • Note that the constructor does not match the class name in your code. Can you please show more exception stack trace? – Alexey Gavrilov Apr 12 '15 at 21:24
  • http://stackoverflow.com/questions/12639791/what-is-the-reason-for-java-lang-illegalargumentexception-no-enum-const-class-e – JamesB Apr 12 '15 at 21:27
  • @AlexeyGavrilov: Typo, thanks ;) I have included a bit more of the stack trace. @JamesB: Yes, but I am telling it to use the static `byText` method to deserialise? – Stine Apr 12 '15 at 21:36

1 Answers1

9

It seems that the problem is not related to Jackson since you are mapping a path parameter, not a payload object.

According to the JAX-RS documentation you can have a static method valueOf or fromString to construct a parameter instance from the string. I suggest to you to rename the byText method to fromString and see what happens.

Alexey Gavrilov
  • 10,593
  • 2
  • 38
  • 48