简体   繁体   English

如何使用Jackson将Java Enums序列化和反序列化为JSON对象

[英]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"

  1. Use the JsonFormat annotation to get Jackson to deserailze the enum as a JSON object. 使用JsonFormat注释使Jackson将枚举作为JSON对象取消。
  2. Create a static constructor accepting a JsonNode and annotate said constructor with @JsonCreator . 创建一个接受JsonNode的静态构造JsonNode并使用JsonNode注释所述构造@JsonCreator
  3. Create a getter for the enum's name. 为枚举的名称创建一个getter。

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.

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