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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.