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
The following may work if the enumeration is an array or not. (Only for deserialization)
package com.stack.model;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import lombok.Data;
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder({ "success", "my-enums" })
public class MyObjectJSON {
@JsonProperty("sucess")
private boolean success;
@JsonProperty("my-enums")
private MyEnum[] myEnums;
static enum MyEnum {
Enum1, Enum2, Enum3, Enum4, EnumN;
private static Map myEnumsMap = new HashMap(5);
static {
myEnumsMap.put("enum1-val", Enum1);
myEnumsMap.put("enum2-val", Enum2);
myEnumsMap.put("enum3-val", Enum3);
myEnumsMap.put("enum4-val", Enum4);
myEnumsMap.put("enumn-val", EnumN);
}
@JsonCreator
public static MyEnum forValue(String value) {
return myEnumsMap.get(value.toLowerCase());
}
}
}
To consider:
@JsonProperty("my-enums") private MyEnum[] myEnums, this is the way to annotate with jackson the field that is of type Enum ( It works if it is an array or not).
MyEnum is the enumeration of the values to be mapped of the JSON object, suppose the following object:
{ "sucess": true, "my-enums": ["enum1-val", "enum3-val"] }
The forValue function allows mapping the string values of the array to Enum, it is annotated with @JsonCreator to indicate a construction factory used in deserialization.