I want to deserialize an enum with Jackson 2.13.1.
I found the following solution.
public enum Type {
TYPEONE("Type1");
private static Map<String, Type> typesMap = new HashMap<>(1);
static {
typesMap.put("type1", TYPEONE);
}
@JsonCreator
public static Type forValue(String value) {
return typesMap.get(value.toLowerCase());
}
private final String label;
Type(String label) {
this.label = label;
}
@JsonValue
public String getLabel() {
return label;
}
}
Still getting the following error:
java.lang.IllegalArgumentException: No enum constant com.cas.cascrt.certificate.model.enums.Type.Type1
at java.base/java.lang.Enum.valueOf(Enum.java:266) ~[na:na]
CodePudding user response:
You don't need to maintain a map. In @JsonCreator method stream through the Type.values(), filter the incoming value and return the enum.
CodePudding user response:
Looks like your error is caused by a typo:
Instead of typesMap.put("type1", TYPEONE);
it should be typesMap.put("Type1", TYPEONE);
to match the TYPEONE("Type1");
.
But anyway: Using a @JsonCreator
, @JsonValue
and a Map
for deserializing/serializing an enum from/to customized strings
is kind of overkill.
You can do it much simpler just by using @JsonProperty
on the enum constants.
public enum Type {
@JsonProperty("Type1")
TYPEONE,
@JsonProperty("Type2")
TYPETWO,
@JsonProperty("Type3")
TYPETHREE;
}