【发布时间】:2015-10-19 18:20:54
【问题描述】:
我正在尝试使用 Jackson 2.5.4 反序列化枚举,但未能成功,我不太了解我的情况。我的输入字符串是驼峰式大小写,我想简单地映射到标准 Enum 约定。
@JsonFormat(shape = JsonFormat.Shape.STRING)
public enum Status {
READY("ready"),
NOT_READY("notReady"),
NOT_READY_AT_ALL("notReadyAtAll");
private static Map<String, Status> FORMAT_MAP = Stream
.of(Status.values())
.collect(toMap(s -> s.formatted, Function.<Status>identity()));
private final String formatted;
Status(String formatted) {
this.formatted = formatted;
}
@JsonCreator
public Status fromString(String string) {
Status status = FORMAT_MAP.get(string);
if (status == null) {
throw new IllegalArgumentException(string + " has no corresponding value");
}
return status;
}
}
我还在吸气剂上尝试了@JsonValue,但无济于事,这是我在其他地方看到的一个选项。他们都爆发了:
com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of ...Status from String value 'ready': value not one of declared Enum instance names: ...
我做错了什么?
【问题讨论】:
-
@FedericoPeraltaSchaffner,我希望这是真的,但它肯定还是会爆炸——我刚刚检查过。我认为它无法处理各种情况。
-
@FedericoPeraltaSchaffner: 相同——“值不是声明的枚举实例名称之一”
-
试试“READY”怎么样?
-
@Simon,如果你所有的 JSON 值都完全匹配,那么它肯定可以工作——但我正在反序列化并且没有更改输入的奢侈!