Close

Jackson JSON - Using @JsonFormat to serialize Java Enum As Object

[Last Updated: Aug 11, 2020]

As seen in the last tutorial Java enums can be serialized by their names or by their ordinals. It is also possible to use JsonFormat.Shape.OBJECT to serialize (but not deserialize) enums as JSON Objects (as if they were POJOs). This only works when @JsonFormat is used on the class level of the target type.

Example

Java Enum

package com.logicbig.example;

import com.fasterxml.jackson.annotation.JsonFormat;

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum EmployeeType {
  FullTime("Full Time"), PartTime("Part Time");

  private String displayName;

  EmployeeType(String displayName) {
      this.displayName = displayName;
  }

  public String getDisplayName() {
      return displayName;
  }
}
public class Employee {
  private String name;
  private EmployeeType employeeType;
    .............
}

Serializing to JSON

public class ExampleMain {
  public static void main(String[] args) throws IOException {
      Employee employee = new Employee();
      employee.setName("Amy");
      employee.setEmployeeType(EmployeeType.PartTime);

      System.out.println("-- before serialization --");
      System.out.println(employee);

      System.out.println("-- after serialization --");
      ObjectMapper om = new ObjectMapper();
      String jsonString = om.writeValueAsString(employee);
      System.out.println(jsonString);
  }
}
-- before serialization --
Employee{name='Amy', employeeType=PartTime}
-- after serialization --
{"name":"Amy","employeeType":{"displayName":"Part Time"}}

Without @JsonFormat

If we remove @JsonFormat from EmployeeType enum:

public enum EmployeeType {
  FullTime("Full Time"), PartTime("Part Time");
 ......
}
-- before serialization --
Employee{name='Amy', employeeType=PartTime}
-- after serialization --
{"name":"Amy","employeeType":"PartTime"}

Example Project

Dependencies and Technologies Used:

  • jackson-databind 2.9.6: General data-binding functionality for Jackson: works on core streaming API.
  • JDK 10
  • Maven 3.5.4

@JsonFormat to serialize Java Enum As Object Select All Download
  • jackson-json-format-enum-as-object
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • EmployeeType.java

    See Also