0

I need to parse any dynamic JSON (In the Kotlin Multiplatform project) to key-value pair and convert it to a nested list after. I started with the default .toMap() function, but it can't go deeper to parse ArrayList<*> Any idea how to do it?

Sample JSON:

{
    "id": "0001",
    "type": "donut",
    "batters":
        {
            "batter":
                [
                    { "id": "1001", "type": "Regular" },
                    { "id": "1004", "type": "Devil's Food" }
                ]
        },
    "topping":
        [
            { "id": "5001", "type": "None" },
            { "id": "5004", "type": "Maple" }
        ]
}

Thanks in advance!

WhiteSpidy.
  • 1,107
  • 1
  • 6
  • 28
nes
  • 81
  • 1
  • 10

1 Answers1

-2

Your @Serializable data class should look like this:

@Serializable
data class MainClass(
    val id: String,
    val type: String,
    val batters: BatterClass,
    val topping: List<ToppingClass>,
)

@Serializable
data class BatterClass(
    val batter: List<BatterClassObject>
)

@Serializable
data class BatterClassObject(
    val id: String,
    val type: String, 
)

@Serializable
data class ToppingClass(
    val id: String,
    val type: String, 
)

Kotlinx.serialization should parse your json without any problems into MainClass.serializable().

Simon
  • 1,657
  • 11
  • 16
  • As I said, I need to parse any dynamic JSON, so it's not possible to create a data class in advance. – nes Mar 29 '22 at 11:03
  • 2
    In that case, just specify root object as `JsonElement`, and deal with it once the serialization to it finishes. – Simon Mar 29 '22 at 13:03
  • @Webfreak That still is not the answer. Answer would be you can't do it with `kotlinx`. "Deserializing" string to `JsonElement` is much like parsing a string at run time without type safety – Farid Sep 29 '22 at 07:19
  • @Farid, if the json is dynamic, there is no other way but to parse it to JsonElement and then making a if-else check. For example: if(JsonElement is JsonObject) else if ( JsonElement is JsonArray)... etc. – Simon Sep 29 '22 at 11:35