鉴于Enum:
public enum CarStatus {
NEW("Right off the lot"),
USED("Has had several owners"),
ANTIQUE("Over 25 years old");
public String description;
public CarStatus(String description) {
this.description = description;
}
}
我们如何设置它以便杰克逊可以将以下格式序列化和反序列化此枚举的实例。
{
"name": "NEW",
"description": "Right off the lot"
}
默认设置是简单地将枚举序列化为字符串。例如"NEW"
。
答案 0 :(得分:14)
JsonFormat
注释让杰克逊将枚举作为JSON对象取消激活。JsonNode
的静态构造函数,并使用@JsonCreator
注释所述构造函数。这是一个例子。
// 1
@JsonFormat(shape = JsonFormat.Shape.Object)
public enum CarStatus {
NEW("Right off the lot"),
USED("Has had several owners"),
ANTIQUE("Over 25 years old");
public String description;
public CarStatus(String description) {
this.description = description;
}
// 2
@JsonCreator
public static CarStatus fromNode(JsonNode node) {
if (!node.has("name"))
return null;
String name = node.get("name").asText();
return CarStatus.valueOf(name);
}
// 3
@JsonProperty
public String getName() {
return name();
}
}