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