0

An enum data type is defined as an attribute of a class.

public class Foo {

  public enum Direction {

    NORTH("north"),
    EAST("east"),
    SOUTH("south");

    public final String label;

    private Direction(String label) {
      this.label = label;
    }

  }

  private Directory direction;
  ...
}

When I parse a Json data to match the class, I get an error

String "east": not one of the values accepted for Enum class: [NORTH, EAST, SOUTH, WEST]

This problem can be resolved by changing the enum data to all low case. If I want to use the Java enum data type convention, what is needed to resolve the problem?

2
  • Build an immutable map to look up the enum values by label (or easier but likely less efficient: loop over all enum values and compare the labels). Commented Oct 23, 2020 at 19:07
  • For enum normally deserialize mapping with enum values like EAST not it's level. You need to write a custom deserializer for enum to deserialize with lebels What you are using for json to class conversion Jackson ? Commented Oct 23, 2020 at 19:09

1 Answer 1

4

If you are using Jackson to deserialise the Foo class, you could:

public class Foo {

  public enum Direction {

    NORTH("north"),
    EAST("east"),
    SOUTH("south");

    @JsonValue
    public final String label;

    private Direction(String label) {
      this.label = label;
    }

  }

  private Direction direction;
  // getter, setter for direction must exist
}

// then deserialise by:
ObjectMapper mapper = new ObjectMapper();
String json = "{\"direction\":\"north\"}";
Foo f = mapper.readValue(json, Foo.class);

This will result in a Foo object with a Direction.NORTH field.
For other possibilities when using Jackson check https://www.baeldung.com/jackson-serialize-enums

Sign up to request clarification or add additional context in comments.

4 Comments

That works. Thanks. I am wondering how Gson handle this situation.
In Gson you can use the @SerializedName annotation which will have the same effect as @JsonValue. See memorynotfound.com/…
Tested and works for Jackson.
You could use the private modifier on the field, jackson does allow that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.