Jackson 枚举序列化和反序列化器?

我正在使用 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

我在这里错过了什么?

原文由 pookieman 发布,翻译遵循 CC BY-SA 4.0 许可协议
阅读 937
2 个回答

如果您希望将 枚举 类与其 JSON 表示完全分离, @xbakesx 指出的序列化器/反序列化器解决方案是一个很好的解决方案。

或者,如果您更喜欢独立的解决方案,基于 @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
    }
}

原文由 Agustí Sánchez 发布,翻译遵循 CC BY-SA 4.0 许可协议

请注意,截至 2015 年 6 月的 提交(Jackson 2.6.2 及更高版本),您现在可以简单地编写:

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

该行为记录在此处: https ://fasterxml.github.io/jackson-annotations/javadoc/2.11/com/fasterxml/jackson/annotation/JsonProperty.html

从 Jackson 2.6 开始,此注释也可用于更改 Enum 的序列化,如下所示:

  public enum MyEnum {
      @JsonProperty("theFirstValue") THE_FIRST_VALUE,
      @JsonProperty("another_value") ANOTHER_VALUE;
 }

作为使用 JsonValue 注释的替代方法。

原文由 tif 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题