杰克逊 - 反序列化一个基枚举

2022-09-02 22:57:30

是否可以反序列化枚举,这些枚举具有基于一的索引?

enum Status {
  Active,
  Inactive
}

{status:1} 表示 Status.Active,但 Jackson 将其设置为 Status.Inactive :(


答案 1
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);        

}}

答案 2

您可以为枚举创建自定义类型 deserialiser:

public enum Status {
    ACTIVE,
    INACTIVE;
    public static Status fromTypeCode(final int typeCode) {
        switch(typeCode) {
        case 1: return ACTIVE;
        case 2: return INACTIVE;
        }
        throw new IllegalArgumentException("Invalid Status type code: " + typeCode);
    }
}

public class StatusDeserializer extends JsonDeserializer<Status> {
    @Override
    public Status deserialize(final JsonParser parser, final DeserializationContext context) throws IOException {
        return Status.fromTypeCode(parser.getValueAsInt());
    }
}

然后,您可以告诉 Jackson 对属性使用您的自定义 deserialiser:

public class WarpDrive {
    private Status status; 
    @JsonDeserialize(using = StatusDeserializer.class)
    public void setStatus(final Status status) {
        this.status = status;
    }
    public Status getStatus() {
        return this.status;
    }
}

您还可以将 Jackson 对象映射器配置为对目标类型的所有实例使用自定义 deserialiser。请参阅 http://wiki.fasterxml.com/JacksonHowToCustomDeserializers