Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 957
Шах Avatar asked Sep 15 '25 22:09

Шах


1 Answers

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 }
    }
}
like image 108
Aleksei Tirman Avatar answered Sep 18 '25 16:09

Aleksei Tirman