编辑: 从Jackson
2.6开始,您可以
@JsonProperty在枚举的每个元素上使用以指定其序列化/反序列化值(请参见此处):
public enum Status { @JsonProperty("ready") READY, @JsonProperty("notReady") NOT_READY, @JsonProperty("notReadyAtAll") NOT_READY_AT_ALL;}(此答案的其余部分仍然适用于旧版本的Jackson)
您应该
@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); // READYSystem.out.println(s2); // NOT_READY_AT_ALL正如工厂方法所期望的那样
String,您必须对字符串使用JSON有效语法,该语法必须带有引号。



