我尝试序列化和反序列化枚举。但 jackson 使用自然枚举顺序值而不是我的。
我使用 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
。
最佳答案
尝试使用 @JsonCreator
公开方法,例如:
@JsonCreator
public static SomeEnum findByCode(final int code){
for (final SomeEnum element : values()) {
if (element.getCode().equals(code)) {
return element;
}
}
return null;
}
关于java - 枚举的反序列化不起作用 - Jackson,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44790034/