问题描述
我使用的是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
我在这里缺少什么?
推荐答案
如果您希望将yor枚举类与其JSON表示完全解耦,则xbakesx指出的serializer / deserializer解决方案是一个很好的解决方案。
The serializer / deserializer solution pointed out by xbakesx is an excellent one if you wish to completely decouple yor 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.
所以利用S的例子以下是一个完整的独立解决方案(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
}
}
这篇关于杰克逊enum序列化和DeSerializer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!