问题

我正在使用JAVA 1.6和Jackson 1.9.9我有一个枚举

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;
    }
}

我添加了一个@JsonValue,这似乎完成了将对象序列化为:

{"event":"forgot password"}

但是当我尝试反序列化时,我得到了一个

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

我在这里想念的是什么?


#1 热门回答(192 赞)

xbakesx指出的串行器/解串器解决方案是一个很好的解决方案,如果你想完全解耦yor enum类和它的JSON表示。

或者,如果你更喜欢自包含的解决方案,则基于@JsonCreator和@JsonValue注释的实现会更方便。

因此,利用Stanley的例子,以下是一个完整的自包含解决方案(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
    }
}

#2 热门回答(135 赞)

请注意,截至2015年6月的this commit(杰克逊2.6.2及更高版本),你现在可以简单地写道:

public enum Event {
    @JsonProperty("forgot password")
    FORGOT_PASSWORD;
}

#3 热门回答(71 赞)

你应该创建一个静态工厂方法,该方法采用单个参数并使用@JsonCreator进行注释(自Jackson 1.2起可用)

@JsonCreator
public static Event forValue(String value) { ... }

阅读更多关于JsonCreator annotationhere的信息。


原文链接