Hello, I previously used Gson and used the "Type" parameter pretty often, to serialize more complex elements.
When i now wanted to switch to kotlinx.serialization, this was the thing that ended up not working for me.
@OptIn(InternalSerializationApi::class)
fun main() {
val pairJson = """
{
"first": "a",
"second": 0
}
""".trimIndent()
println(Json.decodeFromString(serializer<Pair<String, Int>>(), pairJson))
println(Json.decodeFromString(serializer(object : TypeToken<Pair<String, Int>>() {}.type), pairJson))
}
As you can see, when using reified types, it works just fine, but as soon as i try to use type:
kotlinx.serialization.SerializationException: Serializer for class 'Pair' is not found.
Now, I know that TypeToken is a class and weird type generic stuff from Gson, so I am not necessarily asking for a fix.
I just do not know what would be the best way to handle this problem. I suppose implementing the full kotlin reflection library and using
createType
to create generic KTypes?
The type has to be stored in a property, so imagine a
Data
container that needs the type
class Data {
// Allow KClass for simpler JsonElements to be deserialized
val type: Either<KClass<*>, KType<*>>
fun deserialize() { ... }
}