There is a very similar question here - Jackson: Serialize and deserialize enum values as integers which deals with using Jackson to serialize and deserialize enums whose solution is pretty simple by using @JsonValue
annotation.
This does not work in case we have an enum with an integer field like below.
enum State{
GOOD(1), BAD(-1), UGLY(0);
int id;
State(int id) {
this.id = id;
}
}
And if our requirement is to serialize and provide the actual value instead of name()
. Say, something like {"name":"foo","state":1}
representing GOOD for foo. Adding @JsonValue
annotation can help only in case of serialization and fails for deserialization. If we do not have fields, meaning that GOOD=0, BAD=1, UGLY=2, @JsonValue
would be sufficient and Jackson fails to deserialize when fields exist - wrong mapping for 0 and 1 and exception for -1.