Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 225
Gregg Avatar asked Jul 08 '16 13:07

Gregg


People also ask

How can we send enum value in JSON?

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 .

Can enum be used as variable value?

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.

Does JSON support enum?

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.

Can enum values be numbers?

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.


1 Answers

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.

like image 65
Zircon Avatar answered Nov 04 '22 23:11

Zircon