Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

index value outside legal index range when trying to deserialize enum in json

I am trying to de-serialize a json string which has an enum as one of its value.

The enum structure is as follows

ENUM STATUS
{
    ACTIVE(0), INACTIVE(1), EXPIRED(3)// Note here that 2 is not used due to some reasons
}

int status = 0;  
public static Status getNameByValue(final int value) {
        for (final Status s: Status.values()) {
            if (s.status== value) {
                return s;
            }
        }
        return null;
    }
}

When I am trying to read a json string which has this as one of its values as follows through rest

{"name":"Raj","status": 3}

I have got the following exception.

number value (3): index value outside legal index range [0..2]
 at [Source: org.apache.catalina.connector.CoyoteInputStream@9e89a21; line: 1, column: 28] (through reference chain: 

Kindly help me in this regard

like image 735
user3089618 Avatar asked Apr 18 '16 11:04

user3089618


2 Answers

Just annotate the method getNameByValue with @JsonCreator, works for me

ENUM STATUS
{
    ACTIVE(0), INACTIVE(1), EXPIRED(3) // Note here that 2 is not used due to some reasons
}

int status = 0;  

@JsonCreator
public static Status getNameByValue(final int value) {
        for (final Status s: Status.values()) {
            if (s.status== value) {
                return s;
            }
        }
        return null;
    }
}
like image 67
ToYonos Avatar answered Sep 16 '22 21:09

ToYonos


Refer to this : https://github.com/FasterXML/jackson-databind/issues/1626 You need to use @JsonCreator and @JsonValue. @JsonProperty works like an index number when the value is an Integer.

like image 25
Darshit Shah Avatar answered Sep 18 '22 21:09

Darshit Shah