Close

Jackson JSON - Using @JsonEnumDefaultValue to mark enum element as default

[Last Updated: Aug 11, 2020]

JsonEnumDefaultValue annotation can be used on an enum element to define a default (fallback) value used during deserialize. The default enum element value is used if unknown value found in input JSON. This annotation is only applicable when the READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE deserialization feature is enabled.

Example

Example Enum

public enum EmployeeType {
  FullTime,
  PartTime,
  @JsonEnumDefaultValue
  Contractor;
}

Deserializing JSON

In following example we are using a valid value of the enum:

public class ExampleMain {
  public static void main(String[] args) throws IOException {
      String jsonString = "\"FullTime\"";
      System.out.println("-- Json string to deserialize --");
      System.out.println(jsonString);

      ObjectMapper om = new ObjectMapper();
      om.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE);
      EmployeeType type = om.readValue(jsonString, EmployeeType.class);
      System.out.println("-- after deserialization --");
      System.out.println(type);
  }
}
-- Json string to deserialize --
"FullTime"
-- after deserialization --
FullTime

Let's use a value which is not defined in our enum:

public class ExampleMain2 {
  public static void main(String[] args) throws IOException {
      String jsonString = "\"remote\"";
      System.out.println("-- Json string to deserialize --");
      System.out.println(jsonString);

      ObjectMapper om = new ObjectMapper();
      om.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE);
      EmployeeType type = om.readValue(jsonString, EmployeeType.class);
      System.out.println("-- after deserialization --");
      System.out.println(type);
  }
}
-- Json string to deserialize --
"remote"
-- after deserialization --
Contractor

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

@JsonEnumDefaultValue Example Select All Download
  • jackson-json-enum-default-value
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • EmployeeType.java

    See Also