Nofate Nofate - 2 months ago 6
Java Question

Serializing enums with Jackson

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

Finally I found solution myself.

I had to annotate enum with @JsonSerialize(using = OrderTypeSerializer.class) and impelement 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();
  }
}