Best way to handle unknown enum values using Jackson

In this article I want to show you how to handle enums using Jackson. It not as easy as it seems. Jackson can’t handle unknown enum values by default. You have to decide, what to do. If you don’t, your application will fail, when external resource changes and new enum value is added.

How to handle unknown values?

Since Jackson 2.0, you can use READ_UNKNOWN_ENUM_VALUES_AS_NULL feature. Still you will have to handle null, when unknown value appears in deserialized enum.

Since 2.8 there is a better way. Use READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE. This feature allows you, to select a value that will be used by default. Let’s see, how it will look.

Provided examples are in Kotlin and use jackson-module-kotlin 2.12+.

enum class Color {
    @JsonEnumDefaultValue UNKNOWN

data class Pixel(val color: Color)

Don’t forget to enable READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE, when configuring ObjectMapper.

val objectMapper = jacksonMapperBuilder()

And that’s how to handle enums to avoid dealing with errors when new enum values are extended.

when (objectMapper.readValue<Pixel>(jsonString).color) {
    Color.RED -> print("Handle red")
    Color.GREEN -> print("Handle green")
    Color.BLUE -> print("Handle blue")
    Color.UNKNOWN -> print("Handle unknown")

How to handle no value or null?

I showed you, how to handle unknown values. This doesn’t solve handling JSON with no color property or color set to null. Using Kotlin we can set color property to be nullable, but there is a better way. All you need to do is to use default value.

data class Pixel(@JsonSetter(nulls = Nulls.AS_EMPTY) val color: Color = Color.UNKNOWN)

@JsonSetter is set up to handle null as empty value. This way when color property is unset, then default Color.UNKNOWN is used.

You can see full example here.

comments powered by Disqus