一尘不染

用Jackson序列化枚举

spring

我有一个下面的枚举:

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

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

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

我使用了不同的注解,但无法获得这样的结果。


阅读 935

收藏
2020-04-13

共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();
  }
}
2020-04-13