Gregg Gregg - 4 months ago 8
JSON Question

Wanting to get Enum Value instead of name in JSON

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.

Answer

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.

Comments