We use Jackson 1.9.1 to serialize and deserialize JSON request response strings to/from Java objects. Primitive Java types, collection types, and custom objects are (de)serialized without issues. However, I have a problem trying to deserialize JSON string into java enum. JSON string is serialized like so:
"wt":{"wt":100.5,"unit":{"LBS":3}}
Java type for wt is like so:
public class Weight {
protected double weight;
protected Unit unit;
}
I referred to this, this, and this on SO and came up with enum for weight units like 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;
}
}
The problem is, when ever I try to deserialize above mentioned JSON I get this error saying: "Unrecognized field "LBS" (Class a.b.c.d.Weight), not marked as ignorable" Exception stacktrace is like so:
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)
...
My questions are: Is the serialized JSON string for enum seem correct ? What else should I include (or annotate) for the enum to be properly deserialized ?