Search code examples
javaenumsjacksonjsonserializer

Jackson enum Serializing and DeSerializer


I'm using JAVA 1.6 and Jackson 1.9.9 I've got an enum

public enum Event {
    FORGOT_PASSWORD("forgot password");

    private final String value;

    private Event(final String description) {
        this.value = description;
    }

    @JsonValue
    final String value() {
        return this.value;
    }
}

I've added a @JsonValue, this seems to do the job it serializes the object into:

{"event":"forgot password"}

but when I try to deserialize I get a

Caused by: org.codehaus.jackson.map.JsonMappingException: Can not construct instance of com.globalrelay.gas.appsjson.authportal.Event from String value 'forgot password': value not one of declared Enum instance names

What am I missing here?


Solution

  • The serializer / deserializer solution pointed out by @xbakesx is an excellent one if you wish to completely decouple your enum class from its JSON representation.

    Alternatively, if you prefer a self-contained solution, an implementation based on @JsonCreator and @JsonValue annotations would be more convenient.

    So leveraging on the example by @Stanley the following is a complete self-contained solution (Java 6, Jackson 1.9):

    public enum DeviceScheduleFormat {
    
        Weekday,
        EvenOdd,
        Interval;
    
        private static Map<String, DeviceScheduleFormat> namesMap = new HashMap<String, DeviceScheduleFormat>(3);
    
        static {
            namesMap.put("weekday", Weekday);
            namesMap.put("even-odd", EvenOdd);
            namesMap.put("interval", Interval);
        }
    
        @JsonCreator
        public static DeviceScheduleFormat forValue(String value) {
            return namesMap.get(StringUtils.lowerCase(value));
        }
    
        @JsonValue
        public String toValue() {
            for (Entry<String, DeviceScheduleFormat> entry : namesMap.entrySet()) {
                if (entry.getValue() == this)
                    return entry.getKey();
            }
    
            return null; // or fail
        }
    }