Enum的反序列化不起作用 - 杰克逊

时间:2017-06-27 21:15:34

标签: java serialization enums jackson deserialization

我尝试序列化和反序列化枚举。但杰克逊使用自然的Enum订单价值代替我的。

我使用Jackson 2.8.9。

我的测试枚举:

public enum SomeEnum {

    SOME_VAL1(1),

    SOME_VAL2(2),

    SOME_VAL3(3),

    SOME_VAL4(4);

    private final Integer code;

    @JsonCreator
    SomeEnum(@JsonProperty("code") Integer code) {
        this.code = code;
    }

    @JsonValue
    public Integer getCode() {
        return code;
    }

}

这是我测试失败的完整代码:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class Program {

    public enum SomeEnum {

        SOME_VAL1(1),

        SOME_VAL2(2),

        SOME_VAL3(3),

        SOME_VAL4(4);

        private final Integer code;

        @JsonCreator
        SomeEnum(@JsonProperty("code") Integer code) {
            this.code = code;
        }

        @JsonValue
        public Integer getCode() {
            return code;
        }

    }

    public static class EnumWrapper {

        private final SomeEnum someEnumVal;

        public EnumWrapper(@JsonProperty("someEnum") SomeEnum someEnumVal) {
            this.someEnumVal = someEnumVal;
        }

        @JsonProperty("someEnum")
        public SomeEnum getSomeEnumVal() {
            return someEnumVal;
        }
    }

    public static void main(String[] args) throws IOException {

        ObjectMapper mapper = new ObjectMapper();

        String inputJson = mapper.writeValueAsString(new EnumWrapper(SomeEnum.SOME_VAL3));
        EnumWrapper resultEnumWrapper =
                mapper.readValue(inputJson, EnumWrapper.class);

        if (resultEnumWrapper.getSomeEnumVal() != SomeEnum.SOME_VAL3) {
            System.out.println(resultEnumWrapper.getSomeEnumVal());
            System.out.println(inputJson);
            throw new RuntimeException("enum = " + resultEnumWrapper.getSomeEnumVal());
        }
    }
}

为什么我对枚举进行了错误的反序列化?我使用@JsonProperty

2 个答案:

答案 0 :(得分:1)

尝试使用@JsonCreator公开方法,例如:

@JsonCreator
public static SomeEnum findByCode(final int code){
    for (final SomeEnum element : values()) {
        if (element.getCode().equals(code)) {
            return element;
        }
    }
    return null;
}

答案 1 :(得分:0)

如何使用Jackson的面向方法声明并使用输入字符串定义setter,它将在内部实例化枚举?

private SomeEnum someEnum;

public void setSomeEnum(String value ){}