Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to annotate enum fields for deserialization using Jackson json

Tags:

java

json

jackson

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?

Inner class

public enum BooleanField {     BOOLEAN_TRUE        { public String value() { return "1";} },     BOOLEAN_FALSE       { public String value() { return "0";} }, 

Java Bean/Request object

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?

like image 600
rakehell Avatar asked Feb 15 '12 19:02

rakehell


People also ask

How does Jackson deserialize enum?

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: {

How do you serialize an enum?

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.

How are enums represented in json?

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.

Can we pass enum in json?

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 .


1 Answers

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.

like image 69
StaxMan Avatar answered Oct 23 '22 15:10

StaxMan