I try to serialize and deserialize enum. But Jackson uses natural Enum order value instead of my.
I uses Jackson 2.8.9.
My test enum:
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;
}
}
And this is my full code with failed test:
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());
}
}
}
Why I have this wrong deserialization of enum? I uses @JsonProperty
.