Given an 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"
.
Because enums are automatically Serializable (see Javadoc API documentation for Enum), there is no need to explicitly add the "implements Serializable" clause following the enum declaration. Once this is removed, the import statement for the java.
To serialize an enum constant, ObjectOutputStream writes the value returned by the enum constant's name method. To deserialize an enum constant, ObjectInputStream reads the constant name from the stream; the deserialized constant is then obtained by calling the java.
All you have to do is create a static method annotated with @JsonCreator in your enum. This should accept a parameter (the enum value) and return the corresponding enum. This method overrides the default mapping of Enum name to a json attribute .
JsonFormat
annotation to get Jackson to deserailze the enum as a JSON object.JsonNode
and annotate said constructor with @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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With