How to handle Any serialization with kotlinx serialization

796 Views Asked by At

I have a JSON response with a parameter which may be of different types depending on the enum value of another parameter. Example JSON:

[
    {
        "type":1,
        "value":"String"
    },
    {
        "type":2,
        "value": 4
    },
    {
        "type":3,
        "value": [2, 4]
    }
]

How would I go about making a (de)serializer for this? I've seen the docs, but neither the @Polymorphic anotation or the generics seem to work for my usecase. My desired output would be something like:

@Serializable
abstract class MyData(open val type: Int, open val value: Any)
@Serializable
data class StringData(override val type: Int, override val value: String): MyData(type, value)
1

There are 1 best solutions below

2
Abdullah Javed On

Will this work? Will provide more detail if not working.

import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json

@Serializable
data class MyData(val type: Int, val value: Any)

val data = Json.decodeFromString<List<MyData>>("""[
    {
        "type":1,
        "value":"String"
    },
    {
        "type":2,
        "value": 4
    },
    {
        "type":3,
        "value": [2, 4]
    }
]""")

println(data)