Java 枚举的反序列化不起作用-Jackson
我尝试序列化和反序列化枚举。但是Jackson使用自然枚举顺序值而不是我的 我使用Jackson 2.8.9 我的测试枚举:Java 枚举的反序列化不起作用-Jackson,java,serialization,enums,jackson,deserialization,Java,Serialization,Enums,Jackson,Deserialization,我尝试序列化和反序列化枚举。但是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") In
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());
}
}
}
为什么我对enum进行了这种错误的反序列化?我使用
@JsonProperty
尝试使用@JsonCreator
公开方法,例如:
@JsonCreator
public static SomeEnum findByCode(final int code){
for (final SomeEnum element : values()) {
if (element.getCode().equals(code)) {
return element;
}
}
return null;
}
使用Jackson的面向方法的声明,用输入字符串定义setter,这将在内部实例化enum,怎么样
private SomeEnum someEnum;
public void setSomeEnum(String value ){}
您不能在枚举定义之外调用枚举构造函数,因此
@JsonCreator
毫无用处。请改用静态工厂方法。@shmosel jackson使用带帮助反射的构造函数。您不能用反射或任何其他方法从外部构造枚举实例。它可以工作,但有一些问题。首先,它具有O(N)复杂性。其次,我必须为每个枚举编写这样的代码。@Max不是为每个枚举编写的,而是只为那些具有引用变量且需要按引用值查找的枚举编写的。关于O(N),您可以哈希映射枚举中的所有值,并使用get
。除非您的枚举有一百万个值,否则这并不重要。