私は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
ここで何が欠けているのでしょうか?
ベストアンサー1
シリアライザ/デシリアライザソリューションは、フォローenumクラスを JSON 表現から完全に分離したい場合に最適です。
あるいは、自己完結型のソリューションを希望する場合は、@JsonCreator
および@JsonValue
アノテーションに基づく実装の方が便利です。
そこで、この例を参考にして@スタンリー以下は完全な自己完結型ソリューションです (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
}
}