Jackson enum Serializing 和 DeSerializer [英] Jackson enum Serializing and DeSerializer
问题描述
我使用的是 JAVA 1.6 和 Jackson 1.9.9 我有一个枚举
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;
}
}
我添加了一个@JsonValue,这似乎完成了将对象序列化为的工作:
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
我在这里遗漏了什么?
推荐答案
@xbakesx 指出的序列化/反序列化解决方案如果您希望将 enum 类与其 JSON 表示完全分离, 是一个很好的选择.
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.
或者,如果您更喜欢独立的解决方案,基于 @JsonCreator
和 @JsonValue
注释的实现会更方便.
Alternatively, if you prefer a self-contained solution, an implementation based on @JsonCreator
and @JsonValue
annotations would be more convenient.
因此利用 @Stanley 的示例,以下是一个完整的自包含解决方案(Java 6,Jackson 1.9):
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
}
}
这篇关于Jackson enum Serializing 和 DeSerializer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!