user2083529
user2083529

Reputation: 735

Rest controller, providing enum name but saving it's value in database

My problem seems to be quite simple as well as complex at the same time. I have a class Display and it has an enum i.e DisplayMode.

public class Display {

  private DisplayMode mode;
  //getters and setters

  public enum DisplayMode {
    BIG("display.mode.big"),
    SMALL("display.mode.small"),
    MEDIUM("display.mode.medium");

    private String modeValue;

    DisplayMode(String modeValue) {
        this.modeValue = modeValue;
    }

    public String toString() {
        return this.name() + "/" + this.modeValue;
    }

    public String getModeValue() {
        return this.modeValue;
     }
  }
}

Now, I have a rest controller which receives the Display in JSON, i.e

{"display": {"mode": "BIG"}}

And it's getting saved in MongoDB as

{"display": {"mode": "BIG"}}

What i want is, if receive the rest request Display as

{"display": {"mode": "BIG"}} or 
{"display": {"mode": "big"}} or anyCase insensitive value

it should be saved in the database as

{"display": {"mode": "display.mode.big"}}

When I want to read Display out via rest controller, it should be same as saved in the database.

Any solution using serilizers and deserializers oranything else. thanks

Upvotes: 1

Views: 77

Answers (1)

GolamMazid Sajib
GolamMazid Sajib

Reputation: 9437

Use @JsonValue to save with value && @JsonCreator to desrialize.

@JsonValue
final String modeValue() {
    return this.modeValue;
}

For Deserialize:

@JsonCreator
    public static DisplayMode forValue(String v) {
        return Arrays.stream(DisplayMode.values())
                .filter(dm -> dm.name().equalsIgnoreCase(v))
                .findAny().orElse(null);
    }

Upvotes: 1

Related Questions