Skip to content

Enum with JsonValue in 5.X #1690

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

Closed
abhijit911turbo opened this issue Mar 10, 2023 · 1 comment
Closed

Enum with JsonValue in 5.X #1690

abhijit911turbo opened this issue Mar 10, 2023 · 1 comment
Labels
status: declined A suggestion or change that we don't feel we should currently apply

Comments

@abhijit911turbo
Copy link

public enum LaunchType {
HARD("Hard"),
SOFT("Soft");

private final String name;

@Override
@JsonValue
public String toString() {
    return name;
}

}

In Spring data couchbase 4.X, Enums where persisted to database as HARD or SOFT
Once we upgraded to Spring data couchbase 5.X, Enums are persisted to database as Hard or Soft.

Why has the behaviour changed and can we move back to previous behaviour?

@spring-projects-issues spring-projects-issues added the status: waiting-for-triage An issue we've not yet triaged label Mar 10, 2023
@mikereiche
Copy link
Collaborator

mikereiche commented Mar 10, 2023

4.x was incorrectly serializing enums as their name (which would be HARD, SOFT in your case).

serializing was:
Enum.class.isAssignableFrom(value.getClass()) ? ((Enum<?>) value).name()

deserializing was:
Enum.valueOf((Class<Enum>) target, value.toString());

This was not compatible with serializing/deserializing with the Couchbase Java SDK.

The issue was raised and fixed in #1617

Enums are now serialized and deserialized by the ObjectMapper (OtherConverters.EnumToObject and Boolean/Integer/StringToEnumConverter.

If you want your LaunchType to be serialized as HARD, SOFT, then you can create a method that returns that and annotate it with @JsonValue. Likewise, create a method annotated with @JsonCreator that takes those strings and returns the Enums.

@JsonValue
public String name(){
   return super.name(); // I suppose name.toUpperCase() would work as well.
}
@JsonCreator
public LaunchType(String uppercaseName){ 
   for(LaunchType e:LaunchType.values()){
       if(values.name().equals(uppercaseName)){
           name = values.name; // the mixed-case name, not the uppercase name()
           return;
        }
    }
    throw SomeDerializationException(...);
 }

@mikereiche mikereiche added status: declined A suggestion or change that we don't feel we should currently apply and removed status: waiting-for-triage An issue we've not yet triaged labels Mar 13, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
status: declined A suggestion or change that we don't feel we should currently apply
Projects
None yet
Development

No branches or pull requests

3 participants