Search code examples
javaenumsjacksonresteasyfasterxml

RestEasy ignores @JsonCreator method for enum


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.


Solution

  • 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.