EDIT:从 Jackson 2.6 开始,您可以使用@JsonProperty
在枚举的每个元素上指定其序列化/反序列化值(see here https://github.com/FasterXML/jackson-databind/issues/677):
public enum Status {
@JsonProperty("ready")
READY,
@JsonProperty("notReady")
NOT_READY,
@JsonProperty("notReadyAtAll")
NOT_READY_AT_ALL;
}
(这个答案的其余部分对于旧版本的杰克逊仍然有效)
你应该使用@JsonCreator
注释接收一个静态方法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(Collectors.toMap(s -> s.formatted, Function.identity()));
private final String formatted;
Status(String formatted) {
this.formatted = formatted;
}
@JsonCreator // This is the factory method and must be static
public static Status fromString(String string) {
return Optional
.ofNullable(FORMAT_MAP.get(string))
.orElseThrow(() -> new IllegalArgumentException(string));
}
}
这是测试:
ObjectMapper mapper = new ObjectMapper();
Status s1 = mapper.readValue("\"ready\"", Status.class);
Status s2 = mapper.readValue("\"notReadyAtAll\"", Status.class);
System.out.println(s1); // READY
System.out.println(s2); // NOT_READY_AT_ALL
由于工厂方法期望String
,您必须对字符串使用 JSON 有效语法,即引用值。