我们使用 Jackson 1.9.1 对 Java 对象的 JSON 请求响应字符串进行序列化和反序列化。原始 Java 类型、集合类型和自定义对象被(反)序列化而没有问题。但是,我在尝试将 JSON 字符串反序列化为 java 枚举时遇到问题。JSON字符串是这样序列化的:
"wt":{"wt":100.5,"unit":{"LBS":3}}
wt 的 Java 类型是这样的:
public class Weight {
protected double weight;
protected Unit unit;
}
我在 SO 上提到了this、this和this,并提出了重量单位的枚举,如下所示:
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;
}
}
问题是,当我尝试反序列化上述 JSON 时,我收到此错误消息:“无法识别的字段“LBS”(类 abcdWeight),未标记为可忽略”异常堆栈跟踪如下:
Caused by: org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "LBS" (Class a.b.c.d.Weight), not marked as ignorable
at [Source: java.io.ByteArrayInputStream@20172017; line: 1, column: 464] (through reference chain: a.b.c.d.MyRequest["blah"]->a.b.c.d.AnotherType["wt"]->a.b.c.d.Weight["LBS"])
at org.codehaus.jackson.map.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:53)
at org.codehaus.jackson.map.deser.StdDeserializationContext.unknownFieldException(StdDeserializationContext.java:267)
at org.codehaus.jackson.map.deser.std.StdDeserializer.reportUnknownProperty(StdDeserializer.java:673)
at org.codehaus.jackson.map.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:659)
at org.codehaus.jackson.map.deser.BeanDeserializer.handleUnknownProperty(BeanDeserializer.java:1365)
...
我的问题是:枚举的序列化 JSON 字符串是否正确?为了使枚举正确反序列化,我还应该包括(或注释)什么?