使用codehaus.jackson enum类型的deserialize越界异常

Exception in thread "main" org.codehaus.jackson.map.JsonMappingException: Can not construct instance of com.xx.EnumType from number value (4): index value outside legal index range [0..1]
 at [Source: java.io.StringReader@3875c597; line: 1, column: 2] (through reference chain: com.xx.xx["EnumType"])
	at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
	at org.codehaus.jackson.map.deser.StdDeserializationContext.weirdNumberException(StdDeserializationContext.java:249)
	at org.codehaus.jackson.map.deser.std.EnumDeserializer.deserialize(EnumDeserializer.java:96)
	at org.codehaus.jackson.map.deser.std.EnumDeserializer.deserialize(EnumDeserializer.java:23)
	at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:299)
	at org.codehaus.jackson.map.deser.SettableBeanProperty$FieldProperty.deserializeAndSet(SettableBeanProperty.java:579)
	at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:697)
	at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
	at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2732)
	at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1863)

默认的Enum反序列化是按照enmu的顺序来设值,而不是按照value值来反序列化,那就造成超越范围的异常
解决办法是使用@org.codehaus.jackson.annotate.JsonCreator注解

deserialize.configure(DeserializationConfig.Feature.FAIL_ON_NUMBERS_FOR_ENUMS,false);
public enum Status {
ACTIVE(1),
INACTIVE(2);
private final int value;
Status(int v) {
    value = v;
}
@org.codehaus.jackson.annotate.JsonValue
public int value() {
    return value;
}  
@org.codehaus.jackson.annotate.JsonCreator
public static Status fromValue(int typeCode) {
    for (Status c: Status.values()) {
        if (c.value==typeCode) {
            return c;
        }
    }
    throw new IllegalArgumentException("Invalid Status type code: " + typeCode);        
}
}

测试代码

public class MyObj{
private Status status;
public void setStatus(Status s){this.status=s;}
public Status getStatus(){return s;}
}
 
String json ="{\"Status\":1}";
MyObj v = deserialize.readValue(json, MyObj.class);
System.out.println(v.getVouchMoneyType());
参考资料
http://stackoverflow.com/questions/8790389/jackson-deserialize-one-base-enums/12842581?1349965910

原创文章,转载请注明: 转载自海波无痕

本文链接地址: 使用codehaus.jackson enum类型的deserialize越界异常

文章的脚注信息由WordPress的wp-posturl插件自动生成

此条目发表在server分类目录,贴了, , , 标签。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

评论链接可以 移除 nofollow.