Serializing enums with Jackson Serializing enums with Jackson json json

Serializing enums with Jackson


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


@JsonFormat(shape= JsonFormat.Shape.OBJECT)public enum SomeEnum

available since https://github.com/FasterXML/jackson-databind/issues/24

just tested it works with version 2.1.2

answer to TheZuck:

I tried your example, got Json:

{"events":[{"type":"ADMIN"}]}

My code:

@RequestMapping(value = "/getEvent") @ResponseBody  public EventContainer getEvent() {    EventContainer cont = new EventContainer();    cont.setEvents(Event.values());    return cont; }class EventContainer implements Serializable {  private Event[] events;  public Event[] getEvents() {    return events; } public void setEvents(Event[] events) {   this.events = events; }}

and dependencies are:

<dependency>  <groupId>com.fasterxml.jackson.core</groupId>  <artifactId>jackson-annotations</artifactId>  <version>${jackson.version}</version></dependency><dependency>  <groupId>com.fasterxml.jackson.core</groupId>  <artifactId>jackson-core</artifactId>  <version>${jackson.version}</version></dependency><dependency>  <groupId>com.fasterxml.jackson.core</groupId>  <artifactId>jackson-databind</artifactId>  <version>${jackson.version}</version>  <exclusions>    <exclusion>      <artifactId>jackson-annotations</artifactId>      <groupId>com.fasterxml.jackson.core</groupId>    </exclusion>    <exclusion>      <artifactId>jackson-core</artifactId>      <groupId>com.fasterxml.jackson.core</groupId>    </exclusion>  </exclusions></dependency><jackson.version>2.1.2</jackson.version>


I've found a very nice and concise solution, especially useful when you cannot modify enum classes as it was in my case. Then you should provide a custom ObjectMapper with a certain feature enabled. Those features are available since Jackson 1.6.

public class CustomObjectMapper extends ObjectMapper {    @PostConstruct    public void customConfiguration() {        // Uses Enum.toString() for serialization of an Enum        this.enable(WRITE_ENUMS_USING_TO_STRING);        // Uses Enum.toString() for deserialization of an Enum        this.enable(READ_ENUMS_USING_TO_STRING);    }}

There are more enum-related features available, see here:

https://github.com/FasterXML/jackson-databind/wiki/Serialization-featureshttps://github.com/FasterXML/jackson-databind/wiki/Deserialization-Features