我使用JAVA 1.6和Jackson 1.9.9,我有一个enum
public enum Event {
FORGOT_PASSWORD("forgot password");
private final String value;
private Event(final String description) {
this.value = description;
}
@JsonValue
final String value() {
return this.value;
}
}
我已经添加了一个@JsonValue,这似乎做的工作,它序列化对象:
{"event":"forgot password"}
但当我尝试反序列化时,我得到
Caused by: org.codehaus.jackson.map.JsonMappingException: Can not construct instance of com.globalrelay.gas.appsjson.authportal.Event from String value 'forgot password': value not one of declared Enum instance names
我错过了什么?
下面是另一个使用字符串值而不是映射的例子。
public enum Operator {
EQUAL(new String[]{"=","==","==="}),
NOT_EQUAL(new String[]{"!=","<>"}),
LESS_THAN(new String[]{"<"}),
LESS_THAN_EQUAL(new String[]{"<="}),
GREATER_THAN(new String[]{">"}),
GREATER_THAN_EQUAL(new String[]{">="}),
EXISTS(new String[]{"not null", "exists"}),
NOT_EXISTS(new String[]{"is null", "not exists"}),
MATCH(new String[]{"match"});
private String[] value;
Operator(String[] value) {
this.value = value;
}
@JsonValue
public String toStringOperator(){
return value[0];
}
@JsonCreator
public static Operator fromStringOperator(String stringOperator) {
if(stringOperator != null) {
for(Operator operator : Operator.values()) {
for(String operatorString : operator.value) {
if (stringOperator.equalsIgnoreCase(operatorString)) {
return operator;
}
}
}
}
return null;
}
}
注意,在2015年6月的这次提交(Jackson 2.6.2及以上版本)中,你现在可以简单地写:
public enum Event {
@JsonProperty("forgot password")
FORGOT_PASSWORD;
}
行为记录在这里:https://fasterxml.github.io/jackson-annotations/javadoc/2.11/com/fasterxml/jackson/annotation/JsonProperty.html
从Jackson 2.6开始,这个注释也可以用来改变Enum的序列化,如下所示:
public enum MyEnum {
@JsonProperty THE_FIRST_VALUE(“theFirstValue”),
another_value @JsonProperty(“another_value”);
}
作为使用JsonValue注释的替代方法。