Skip to content

Specifying Enum value serialization using @JsonPropertyΒ #677

@allenchen1154

Description

@allenchen1154

Currently, if I want to deserialize an enum with a value that isn't its Enum.name(), I can do either

public enum TestEnum {
    VALUE_ONE("value1");

    private String valueInJson;

    private TestEnum(String valueInJson) {
        this.valueInJson = valueInJson;
    }

    @JsonCreator
    public static TestEnum getEnumFromValue(String value) {
        for (TestEnum testEnum : values()) {
            if (testEnum.valueInJson.equals(value)) {
                return testEnum;
            }
        }
        throw new IllegalArgumentException();
    }
}

or, using DeserializationFeature.READ_ENUMS_USING_TO_STRING,

public enum TestEnum {
    VALUE_ONE("value1");

    private String valueInJson;

    private TestEnum(String valueInJson) {
        this.valueInJson = valueInJson;
    }

    @Override
    public String toString() {
        return valueInJson;
    }
}

This seems like a lot of boilerplate - is there a simpler way to do this, similar to how Gson handles it?

public enum TestEnum {
    @SerializedName("value1")
    VALUE_ONE
}

It's both more concise and handles both serialization and deserialization.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions