Search code examples
kotlinjackson

Serialize enum field into JSON in Kotlin


I've got a stupid question that stunned me a bit. I have an enum and a data class like this:

enum class MyEventType(val typeName: String) {
    FIRST("firstEventReceived")
}

data class MyEvent(
    val id: String,
    val event: MyEventType
)

I need to send this as a json string, but common desearilizer makes such a json

{ 
    "id": "identifier",
    "event": "FIRST"
}

but i need

{ 
    "id": "identifier",
    "event": "firstEventReceived"
}

As far as i understand, kotlin allows to override getter in data class, but i didn't succeed in it... Trying to make

data class MyEvent(
    val id: String
) {
    val event: MyEventType get() event.typeName
}

but i've missed something, i guess...


Solution

  • The simplest way is probably to annotate the property with @JsonValue:

    enum class MyEventType(@JsonValue val typeName: String) {
        FIRST("firstEventReceived")
    }
    
    data class MyEvent(
        val id: String,
        val event: MyEventType
    )
    
    
    fun main() {
        MyEvent(id = "foo", event = MyEventType.FIRST)
            .let { jacksonObjectMapper().writeValueAsString(it) }
            .let { println(it) }
    }
    

    Prints:

    {"id":"foo","event":"firstEventReceived"}