0

I have the following enum:

public enum ChangeMode {

    None(1), Add(2), Update(3), Delete(4);

    // String value
    public String getStringValue() {
        return name();
    }

    public static ChangeMode getEnumValue(String v) {
        return valueOf(v);
    }

    public static ChangeMode getEnumValue(int intValue) {
        for (ChangeMode x : values())
            if (Objects.equals(x.intValue, intValue))
                return x;

        return null;
    }

    // Int value
    private int intValue;

    private ChangeMode(int intValue) {
        this.intValue = intValue;
    }

    public int getIntValue() {
        return this.intValue;
    }
}

Notice the enum values start from 1-4 and not 0-3.

I'm using Wildfly and Jackson.

When I'm getting the value 4 from the client JSON (using HTTP POST) I'm getting the following error:

Can not construct instance of com.ta9.enums.ChangeMode from number value (4): index value outside legal index range [0..3] at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@55a6e779; line: 770, column: 26] (through reference chain:

Dor Cohen
  • 16,769
  • 23
  • 93
  • 161
  • 1
    That is most likely because the code that does the deserialization looks up the enum constant by ordinal and not through your `getEnumValue(int)` method which is supposed to do the conversion. – Jesper Jul 28 '16 at 13:52
  • @Jesper Indeed this is the problem, do you have an idea how to solve this? – Dor Cohen Jul 28 '16 at 13:54
  • 1
    Have a look at this question: [Jackson enum Serializing and DeSerializer](http://stackoverflow.com/questions/12468764/jackson-enum-serializing-and-deserializer) or this one: [How to annotate enum fields for deserialization using Jackson json](http://stackoverflow.com/questions/9300191/how-to-annotate-enum-fields-for-deserialization-using-jackson-json) – Jesper Jul 28 '16 at 13:55
  • You are returning `x` which is the ordinal value instead of the contained field value – jr593 Jul 28 '16 at 14:02
  • @jr593 That is incorrect, `x` is a `ChangeMode` value, not an integer. This is Java, not C# or C++ where an `enum` is a glorified integer. – Jesper Jul 28 '16 at 14:28
  • @Jesper Quite correct, my bad – jr593 Jul 28 '16 at 15:53

0 Answers0