Jackson – Serialize Enums as JSON Objects

1. Overview

This quick tutorial will show how to control the way Java Enums are serialized to JSON output with Jackson 2.

2. Controlling the Enum Representation

Let’s define the following Enum:

public enum Type {
    TYPE1(1, "Type A"), TYPE2(2, "Type 2");

    private Integer id;
    private String name;

    private Type(final Integer id, final String name) {
        this.id = id;
        this.name = name;
    }

    // standard getters and setters
}

2.1. Default Enum Representation

By default, Jackson will represent Java Enums as simple String – for example:

new ObjectMapper().writeValueAsString(Type.TYPE1);

Will result in:

"TYPE1"

When marshalling this ENUM to a JSON Object would look like this:

{"name":"Type A","id":1}

2.2. Enum as Json Object

Starting with Jackson 2.1.2 – the is now a configuration option that can handle this kind of representation – via the @JsonFormat annotation, at the Enum level:

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum Type { ... }

This will lead to the correct result when serializing the enum above:

{"name":"Type A","id":1}

2.3. Custom Serializer for Enum

Before Jackson 2.1.2, or if even more customization is required for the enum – we can use a custom Jackson serializer – first we’ll need to define it:

public class TypeSerializer extends JsonSerializer<TypeEnum> {

    public void serialize
      (TypeEnumWithCustomSerializer 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();
    }
}

We will now tie together the serializer and the class it applies to:

@JsonSerialize(using = TypeSerializer.class)
public enum TypeEnum { ... }

3. Conclusion

This article illustrated how to gain better control over the serialization process and format of Java Enums.

The implementation of all these examples and code snippets can be found in my github project – this is an Eclipse based project, so it should be easy to import and run as it is.

I usually post about Dev stuff on Google+ - you can follow me there:

Free eBook - REST Services with Spring
Join more than 2,200 engineers!
  • TatuSaloranta

    Good stuff. Two more suggestions for things to include: @JsonValue (serialize enum using value a method returns — yes, you can define custom methods for enum), and @JsonCreator for indicating factory method (that takes a single String arg) to use for reading Enums back.