I am using REST web service/Apache Wink with Jackson 1.6.2. How do I annotate an enum field so that Jackson deserializes it?
public enum BooleanField { BOOLEAN_TRUE { public String value() { return "1";} }, BOOLEAN_FALSE { public String value() { return "0";} },
BooleanField locked; public BooleanField getLocked() {return locked;}
The Jackson docs state that it can do this via @JsonValue
/@JsonCreator
but provides no examples.
Anyone willing to spill the (java)beans, as it were?
All the methods annotated by @JsonCreator are invoked by Jackson for getting an instance of the enclosing class. In order to deserialize the JSON String to Enum by using the @JsonCreator, we will define the forValues() factory method with the @JsonCreator annotation. We have the following JSON string to deserialize: {
To serialize an enum constant, ObjectOutputStream writes the value returned by the enum constant's name method. To deserialize an enum constant, ObjectInputStream reads the constant name from the stream; the deserialized constant is then obtained by calling the java.
JSON has no enum type. The two ways of modeling an enum would be: An array, as you have currently. The array values are the elements, and the element identifiers would be represented by the array indexes of the values.
All you have to do is create a static method annotated with @JsonCreator in your enum. This should accept a parameter (the enum value) and return the corresponding enum. This method overrides the default mapping of Enum name to a json attribute .
If you are using Jackson 1.9, serialization would be done by:
public enum BooleanField { BOOLEAN_TRUE("1") ; // either add @JsonValue here (if you don't need getter) private final String value; private BooleanField(String value) { this.value = value; } // or here @JsonValue public String value() { return value; }
so change you need is to add method to Enum type itself, so all values have it. Not sure if it would work on subtype.
For @JsonCreator
, having a static factory method would do it; so adding something like:
@JsonCreator public static BooleanField forValue(String v) { ... }
Jackson 2.0 will actually support use of just @JsonValue
for both, including deserialization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With