Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide annotation on Enum constant that is used on JSON mapping #1259

Closed
nbartels opened this issue Nov 6, 2022 · 1 comment
Closed

Provide annotation on Enum constant that is used on JSON mapping #1259

nbartels opened this issue Nov 6, 2022 · 1 comment
Assignees
Milestone

Comments

@nbartels
Copy link
Contributor

nbartels commented Nov 6, 2022

Our JSON mapper has support for enums as types in our objects, but we only support the constant itself or an upper case version. This means if Facebook uses the enum value test the enum constant may be test or TEST.

This is ok so far, but we are not that flexible in naming our enum constants. To improve this, I suggest using an annotation on the constants and use the provided value in the annotation for the mapping in both directions.

GSON uses some similar approach:

enum Flavor {
    @SerializedName("van")
    VANILLA,
    @SerializedName("choc")
    CHOCOLATE
}

To access this value, there is this method:

String getSerializedName(Enum<?> e) {
    try {
        Field f = e.getClass().getField(e.name());
        SerializedName a = f.getAnnotation(SerializedName.class);
        return a == null ? null : a.value();
    } catch (NoSuchFieldException ignored) {
        return null;
    }
}
nbartels added a commit that referenced this issue Dec 19, 2022
@nbartels
Copy link
Contributor Author

The enum constants can be annotated with our Facebook annotation and can have a different value.

For example @Facebook("test") FOO will convert the incoming String test to the FOO enum, if the enum is used in a type and the other way around. The FOO constant will be converted to the String "test" on converting the object to JSON.

Important: It is not necessary to set the annotation to allow the usage of the constant. The former default behavior is still active.

@nbartels nbartels self-assigned this Dec 19, 2022
@nbartels nbartels added this to the 2022.11.0 milestone Dec 19, 2022
@github-actions github-actions bot locked as resolved and limited conversation to collaborators Mar 28, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

1 participant