Parse a dynamic nested JSON into Map<*, *> using Kotlinx.serialization

917 views Asked by At

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!

1

There are 1 answers

4
Simon On

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().