8

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.

Gregg
  • 34,973
  • 19
  • 109
  • 214
  • You tagged Jackson, though I'm not sure what version you're using. I think if you annotate with @JsonValue above your toString it would use that as the value for the enum. Or you could use a custom serializer. – Zircon Jul 08 '16 at 14:02
  • I'll try the `@JsonValue` and report back. Thanks! – Gregg Jul 08 '16 at 14:03
  • That worked! Submit that as the answer and I'll accept it. Thanks again. – Gregg Jul 08 '16 at 14:04
  • Just wondering: why would you want to do that? If you are concerned that using Store versus S is a problem for you; don't you think that JSON itself might already be a problem? Like in: "geez, I don't mind using that protocol that contains soooo much overhead, but heck, my enums, they use up too much bytes in there?" – GhostCat Jul 08 '16 at 14:07
  • 1
    Is it not the advantage of JSON to offer the same data as XML but in a smaller format? It would make sense that he would want his values to be as small as possible if working over poor network conditions. – Zircon Jul 08 '16 at 14:10
  • It's literally about code readability as well as what the client needs for the representation. If all I had were E, S, etc in the enum, there would have to be documentation on what each represent. It is just kind of self documenting this way and keeps options open for alternative rendering later if we need it. – Gregg Jul 08 '16 at 14:15

1 Answers1

7

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.

Zircon
  • 4,677
  • 15
  • 32