我正在使用JAVA 1.6和Jackson 1.9.9我有一个枚举
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我添加了一个@JsonValue,这似乎完成了将对象序列化为:
{"event":"forgot password"}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试反序列化时,我得到了一个
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
Run Code Online (Sandbox Code Playgroud)
我在这里错过了什么?
我们使用Jackson 1.9.1对JSON请求响应字符串进行序列化和反序列化.原始Java类型,集合类型和自定义对象(序列化)没有问题.但是,我在尝试将JSON字符串反序列化为java枚举时遇到问题.JSON字符串是这样序列化的:
"wt":{"wt":100.5,"unit":{"LBS":3}}
Run Code Online (Sandbox Code Playgroud)
wt的Java类型是这样的:
public class Weight {
protected double weight;
protected Unit unit;
}
Run Code Online (Sandbox Code Playgroud)
我提到了这个,这个,以及这个在SO上,并提出了重量单位的枚举,如下:
public enum Unit {
KG("kg"),
GM("gm"),
LBS("lbs"),
OZ("oz");
private String value;
private WeightMeasurementUnit(String value) { this.value = value; }
@JsonValue
public String getValue() { return this.value; }
@JsonCreator
public static Unit create(String val) {
Unit[] units = Unit.values();
for (Unit unit : units) {
if (unit.getValue().equals(val)) {
return unit;
}
}
return LBS;
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,当我尝试反序列化上面提到的JSON时,我得到这个错误说:"无法识别的字段"LBS"(类abcdWeight),没有标记为可忽略"异常堆栈跟踪是这样的:
Caused by: …Run Code Online (Sandbox Code Playgroud)