@JsonValue annotation in Kotlin's enum class' value property

Viewed 6827

I'm unable to apply the Jackson's @JsonValue annotation on the value parameter of enum class:

enum class CancellationReason(@JsonValue val code: String) {
    CUSTOMER_RESIGNED("20"),
    ERRORS_IN_FOO("21"),
    ERRORS_IN_BAR("24");
}

The error message states: This annotation in not applicable to target 'value parameter'. What's the problem?

2 Answers

You can upgrade jackson-module-kotlin to version 2.9.0, and the error will be gone, because the @JsonValue annotation gets a target FIELD in that version.

Alternatively, fix that by specifying the annotation use-site target by adding @get::

enum class CancellationReason(@get:JsonValue val code: String) {
    CUSTOMER_RESIGNED("20"),
    ERRORS_IN_FOO("21"),
    ERRORS_IN_BAR("24");
}

As per this document, you can serialize the enum constant (enum object) as Json in Kotlin by annotating the enum property with @JsonValue or @JsonFormat (if you use jackson library version < 2.9). As hotkey mentioned, upgrade your Jackson library to 2.9.0. Alternatively you can use @JsonFormat annotation

enum class Event(@JsonFormat(shape = JsonFormat.Shape.OBJECT) val event: String) {
    START("start"),
    END("end"),
    RESCHEDULE("rescheduled")
}
Related