简体   繁体   中英

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

By default most frameworks will look to serialize/deserialize enums by its Ordinal number.

You will need to tell the deserializer how to understand your enum, for ex if you are using Jackson for mapping to and from JSON, you can refer to the following answer , though this answer is for serializing, you can follow the same approach for deserializing.

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;
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM