如何在 Ktor 中以小写形式序列化/反序列化枚举?

Шах*_*Шах 2 kotlin json-serialization ktor

我在我的应用程序中使用Ktor 序列化,下面是build.gradle中的依赖项:

dependencies {
    // ...
    implementation "io.ktor:ktor-serialization:$ktor_version"
}
Run Code Online (Sandbox Code Playgroud)

并在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
        })
    }
    // ...
}
Run Code Online (Sandbox Code Playgroud)

一切都很完美,但枚举......例如,我有下一个:

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

    companion object {
        fun valueOf(value: Int) = values().find { it.id == value }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我序列化这个枚举实例,Ktor将输出如下内容:

{
    "gender": "MALE"
}
Run Code Online (Sandbox Code Playgroud)

如何在不重命名枚举成员的情况下将其改成小写?

PS另外,我无法更改Int类型String,因为它代表数据库 ID。

Ale*_*man 7

您可以为枚举常量添加SerialName注释来覆盖 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 }
    }
}
Run Code Online (Sandbox Code Playgroud)