gpt4 book ai didi

java - Jackson 枚举序列化和反序列化

转载 作者:行者123 更新时间:2023-12-01 23:11:02 24 4
gpt4 key购买 nike

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

我在这里缺少什么?

最佳答案

@xbakesx指出的串行器/解串器解决方案如果您希望将 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
}
}

关于java - Jackson 枚举序列化和反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58376418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com