https://kotlinlang.org logo
#serialization
Title
# serialization
i

iamthevoid

03/28/2023, 7:53 AM
I want to parse a json that looks like:
Copy code
{
   "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?
a

Adam S

03/28/2023, 9:21 AM
what about
dynamicKey
is dynamic? The value? The name? You can try using
JsonElement
Copy code
@Serializable
data class MyData(
  val staticKey: String,
  val dynamicKey: JsonElement,
)
And then you can use a
when () {}
statement to decode it
i

iamthevoid

03/28/2023, 9:23 AM
Name of field is dynamic. It is free api, so i can't influence on api (
a

Adam S

03/28/2023, 9:26 AM
the easiest way is to just decode the whole response to a
JsonObject
Copy code
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)
}
if you know the expected name & value of
dynamicKey
, 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 better
i

iamthevoid

03/28/2023, 9:39 AM
I'd want to find easiest way, because i does not want to spend a much time for it. So i'll try JsonObject, thanks
8 Views