I've got the following enum:
public enum NotificationType {
Store("S"),
Employee("E"),
Department("D"),
All("A");
public String value;
NotificationType(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
@JsonCreator
public static NotificationType fromValue(String value) {
for (NotificationType type : NotificationType.values()) {
if (type.value.equals(value)) {
return type;
}
}
throw new IllegalArgumentException();
}
}
I've created a converter so that when the enum is saved to the database, it persists the value (S, E, D or A) instead of the name. And I can POST
json to the controller with the value and it binds to the object correctly.
However, when I render the JSON from a GET
it is still displaying the name (Employee, Store, etc) and I would prefer that it still show the value.
All you have to do is create a static method annotated with @JsonCreator in your enum. This should accept a parameter (the enum value) and return the corresponding enum. This method overrides the default mapping of Enum name to a json attribute .
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it.
JSON has no enum type. The two ways of modeling an enum would be: An array, as you have currently. The array values are the elements, and the element identifiers would be represented by the array indexes of the values.
Numeric enums are number-based enums i.e. they store string values as numbers. Enums are always assigned numeric values when they are stored. The first value always takes the numeric value of 0, while the other values in the enum are incremented by 1.
Because your toString
method returns the value you want to use to represent your enum, you can annotate it with @JsonValue
to tell Jackson that the return value represents the value of the enum.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With