Jackson: Serialize and deserialize enum values as integers
You can use setting
objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_INDEX);
See https://github.com/FasterXML/jackson-databind/blob/master/src/test/java/com/fasterxml/jackson/databind/ser/TestEnumSerialization.java for complete test cases
Thanks to tip at https://righele.it/2016/01/30/jackson-deserialization-from-json-to-java-enums/
Yet another way:
public enum State {
@JsonProperty("0")
OFF,
@JsonProperty("1")
ON,
@JsonProperty("2")
UNKNOWN
}
However, this will produce {"state" : "1"}
instead of {"state" : 1}
(string, not numeric). In most cases it's OK
It should work by specifying JsonValue
mapper.
public enum State {
OFF,
ON,
UNKNOWN;
@JsonValue
public int toValue() {
return ordinal();
}
}
This works for deserialization also, as noted in Javadoc of @JsonValue
annotation:
NOTE: when use for Java enums, one additional feature is that value returned by annotated method is also considered to be the value to deserialize from, not just JSON String to serialize as. This is possible since set of Enum values is constant and it is possible to define mapping, but can not be done in general for POJO types; as such, this is not used for POJO deserialization
You can use in this way
import com.fasterxml.jackson.annotation.JsonFormat;
@JsonFormat(shape = JsonFormat.Shape.NUMBER)
public enum State {
OFF,
ON,
UNKNOWN
}