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.
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.
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.
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...
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(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With