I am new to Kotlin and even newer to Kotlin Serialization and I am trying to convert a Kotlin data class to JSON. Look at the following sample code:
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JSON
fun main(args: Array<String>) {
println(JSON.stringify(BaseClass1("abc")))
println(JSON.stringify(BaseClass2("abc")))
}
@Serializable
data class BaseClass1(
val a: String
)
@Serializable
data class BaseClass2(
val a: Any
)
The output is:
{"a":"abc"}
{"a":["kotlin.String","abc"]}
So I save a String in a variable of the type Any (which should be perfectly valid). However, this results in the serialized value being an array of the type and the value. This also happens with other classes and subclasses (when I extend the field's type for example).
How can I get stringify to always use the value, regardless of the field's actual type? I want the second stringify result of the program above to match the first one.