Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 286
Nofate Avatar asked Oct 14 '11 11:10

Nofate


People also ask

Can enum be serialized?

The serialized form of an enum constant consists solely of its name; field values of the constant are not present in the form. To serialize an enum constant, ObjectOutputStream writes the value returned by the enum constant's name method.

Can you serialize an enum C#?

In C#, JSON serialization very often needs to deal with enum objects. By default, enums are serialized in their integer form. This often causes a lack of interoperability with consumer applications because they need prior knowledge of what those numbers actually mean.

Can enum be mocked?

Extending the enum to add an extra value is not possible, and just mocking the equals method to return false won't work either because the bytecode generated uses a jump table behind the curtains to go to the proper case...


1 Answers

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();   } } 
like image 173
Nofate Avatar answered Sep 24 '22 15:09

Nofate