Reputation: 71
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?
Upvotes: 0
Views: 4442
Reputation: 156
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
Upvotes: 4