[英]How to serialize and deserialize Java Enums as JSON objects with Jackson
Given an Enum: 鉴于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;
}
}
How can we set it up so Jackson can serialize and deserialize an instance of this Enum into and from the following format. 我们如何设置它,以便杰克逊可以将此枚举的实例序列化和反序列化为以下格式。
{
"name": "NEW",
"description": "Right off the lot"
}
The default is to simply serialize enums into Strings. 默认是简单地将枚举序列化为字符串。 For example
"NEW"
. 例如
"NEW"
。
JsonFormat
annotation to get Jackson to deserailze the enum as a JSON object. JsonFormat
注释使Jackson将枚举作为JSON对象取消。 JsonNode
and annotate said constructor with @JsonCreator
. JsonNode
的静态构造JsonNode
并使用JsonNode
注释所述构造@JsonCreator
。 Here's an example. 这是一个例子。
// 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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.