简体   繁体   中英

How to serialize and deserialize Java Enums as JSON objects with Jackson

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" .

  1. Use the JsonFormat annotation to get Jackson to deserailze the enum as a JSON object.
  2. Create a static constructor accepting a JsonNode and annotate said constructor with @JsonCreator .
  3. Create a getter for the enum's name.

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM