Serializing enums with Jackson

Nofate picture Nofate · Oct 14, 2011 · Viewed 101.4k times · Source

I have an Enum desrcibed below:

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

I return enum array with my controller ( new OrderType[] {UNKNOWN,TYPEA,TYPEB,TYPEC};), and Spring serializes it into the following json string:

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

What is the best approach to force Jackson to serialize enums just like POJOs? E.g.:

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

I played with different annotations but couldn't manage to get such result.

Answer

Nofate picture Nofate · Oct 14, 2011

Finally I found solution myself.

I had to annotate enum with @JsonSerialize(using = OrderTypeSerializer.class) and implement custom serializer:

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