简体   繁体   English

尝试在json中反序列化枚举时,索引值超出合法索引范围

[英]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. 我试图反序列化一个jum字符串,其中枚举作为其值之一。

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 当我试图读取一个json字符串时,通过休息将其作为其值之一

{"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. 您将需要告诉解串器如何理解您的枚举,例如,如果您使用Jackson进行JSON映射,您可以参考以下答案 ,虽然这个答案用于序列化,但您可以按照相同的方法进行反序列化。

Just annotate the method getNameByValue with @JsonCreator , works for me 只需使用getNameByValue注释方法@JsonCreator ,适合我

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. 请参阅: https//github.com/FasterXML/jackson-databind/issues/1626您需要使用@JsonCreator和@JsonValue。 @JsonProperty works like an index number when the value is an Integer. 当值为Integer时,@ JsonProperty就像索引号一样工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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