使用 Jackson 序列化枚举

2022-08-31 11:01:16

我有一个Enum在下面描述:

public enum OrderType {

  UNKNOWN(0, "Undefined"),
  TYPEA(1, "Type A"),
  TYPEB(2, "Type B"),
  TYPEC(3, "Type C");

  private Integer id;
  private String name;

  private WorkOrderType(Integer id, String name) {
    this.id = id;
    this.name = name;
  }

  //Setters, getters....
}

我用我的控制器()返回枚举数组,Spring将其序列化为以下json字符串:new OrderType[] {UNKNOWN,TYPEA,TYPEB,TYPEC};

["UNKNOWN", "TYPEA", "TYPEB", "TYPEC"] 

迫使 Jackson 像 POJO 一样序列化枚举的最佳方法是什么?例如:

[
  {"id": 1, "name": "Undefined"},
  {"id": 2, "name": "Type A"},
  {"id": 3, "name": "Type B"},
  {"id": 4, "name": "Type C"}
]

我玩了不同的注释,但无法得到这样的结果。


答案 1

最后,我自己找到了解决方案。

我必须使用自定义序列化程序注释枚举并实现自定义序列化程序:@JsonSerialize(using = OrderTypeSerializer.class)

public class OrderTypeSerializer extends JsonSerializer<OrderType> {

  @Override
  public void serialize(OrderType value, JsonGenerator generator,
            SerializerProvider provider) throws IOException,
            JsonProcessingException {

    generator.writeStartObject();
    generator.writeFieldName("id");
    generator.writeNumber(value.getId());
    generator.writeFieldName("name");
    generator.writeString(value.getName());
    generator.writeEndObject();
  }
}

答案 2
@JsonFormat(shape= JsonFormat.Shape.OBJECT)
public enum SomeEnum

https://github.com/FasterXML/jackson-databind/issues/24 年起可用

刚刚测试过它适用于版本2.1.2

对TheZuck的回答

我尝试了你的例子,得到了Json:

{"events":[{"type":"ADMIN"}]}

我的代码:

@RequestMapping(value = "/getEvent") @ResponseBody
  public EventContainer getEvent() {
    EventContainer cont = new EventContainer();
    cont.setEvents(Event.values());
    return cont;
 }

class EventContainer implements Serializable {

  private Event[] events;

  public Event[] getEvents() {
    return events;
 }

 public void setEvents(Event[] events) {
   this.events = events;
 }
}

和依赖关系是:

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>${jackson.version}</version>
</dependency>

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>${jackson.version}</version>
</dependency>

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>${jackson.version}</version>
  <exclusions>
    <exclusion>
      <artifactId>jackson-annotations</artifactId>
      <groupId>com.fasterxml.jackson.core</groupId>
    </exclusion>
    <exclusion>
      <artifactId>jackson-core</artifactId>
      <groupId>com.fasterxml.jackson.core</groupId>
    </exclusion>
  </exclusions>
</dependency>

<jackson.version>2.1.2</jackson.version>