Java JsonEnumDefaultValue-class And Method Code Example


Here is an example of using the JsonEnumDefaultValue annotation from the Apache Commons IO library to specify a default value for an enumeration when serializing it to JSON:

import org.apache.commons.io.output.JsonEnumDefaultValue;
import com.fasterxml.jackson.annotation.JsonValue;

public enum MyEnum {
    VALUE_1,
    VALUE_2,
    @JsonEnumDefaultValue
    VALUE_3;

    @JsonValue
    public String getValue() {
        return name();
    }
}

In this example, the VALUE_3 enumeration constant is annotated with @JsonEnumDefaultValue, which means that when serializing the MyEnum enumeration to JSON, the VALUE_3 constant will be used if no other value is specified.

Note that you will need to include the com.fasterxml.jackson.annotation.JsonValue as well,

and also make sure that you are using jackson as serializer.