iamthevoid
03/28/2023, 7:53 AM{
"staticKey": "strungValue",
"dynamicKey": { map string : double }
}
problem is that the dynamicKey
is really dynamic and can change from request to request (i know what it be in each request, because it equals request param). What is the best way to deserialize structure like that?Adam S
03/28/2023, 9:21 AMdynamicKey
is dynamic? The value? The name?
You can try using JsonElement
@Serializable
data class MyData(
val staticKey: String,
val dynamicKey: JsonElement,
)
And then you can use a when () {}
statement to decode itiamthevoid
03/28/2023, 9:23 AMAdam S
03/28/2023, 9:26 AMJsonObject
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
fun main() {
val obj = Json.decodeFromString<JsonObject>(
"""
{
"staticKey": "strungValue",
"dynamicKey": { map string : double }
}
""".trimIndent()
)
println(obj)
}
Adam S
03/28/2023, 9:28 AMdynamicKey
, and if you really really wanted to decode to a class, you could try writing a custom serializer https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#hand-written-composite-serializer
but I do not recommend this, I think it will be very difficult and not really worth it. JsonObject is betteriamthevoid
03/28/2023, 9:39 AMephemient
03/28/2023, 1:31 PM