Home > database >  How to serialize/deserialize enums in/from a lower case in Ktor?
How to serialize/deserialize enums in/from a lower case in Ktor?

Time:04-13

I use Ktor serialization in my app, below is a dependency in build.gradle:

dependencies {
    // ...
    implementation "io.ktor:ktor-serialization:$ktor_version"
}

And set up it in Application.kt:

fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)

@Suppress("unused")
fun Application.module(@Suppress("UNUSED_PARAMETER") testing: Boolean = false) {
    // ...
    install(ContentNegotiation) {
        json(Json {
            prettyPrint = true
        })
    }
    // ...
}

All works perfectly but enumerations... For example, I have the next one:

enum class EGender(val id: Int) {
    FEMALE(1),
    MALE(2);

    companion object {
        fun valueOf(value: Int) = values().find { it.id == value }
    }
}

If I will serialise this enum instance, Ktor will output a something like:

{
    "gender": "MALE"
}

How to make it in a lower case without renaming enumeration members?

P.S. Also I can't change Int to String type cuz it represents database IDs.

CodePudding user response:

You can add the SerialName annotation for enum constants to override names in JSON:

@kotlinx.serialization.Serializable
enum class EGender(val id: Int) {
    @SerialName("female")
    FEMALE(1),
    @SerialName("male")
    MALE(2);

    companion object {
        fun valueOf(value: Int) = values().find { it.id == value }
    }
}
  • Related