我在我的应用程序中使用Ktor 序列化,以下是build.gradle中的依赖项:
dependencies {
// ...
implementation "io.ktor:ktor-serialization:$ktor_version"
}
并在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
})
}
// ...
}
一切正常,但枚举...例如,我有下一个:
enum class EGender(val id: Int) {
FEMALE(1),
MALE(2);
companion object {
fun valueOf(value: Int) = values().find { it.id == value }
}
}
如果我要序列化这个枚举实例,Ktor将输出如下内容:
{
"gender": "MALE"
}
如何在不重命名枚举成员的情况下使其小写?
PS另外,我无法更改Int
为String
类型,因为它代表数据库 ID。
您可以为枚举常量添加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 }
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句