jaqxues
10/15/2020, 6:38 PM@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() { ... }
}
rnett
10/15/2020, 6:46 PMdecodeFromString
).
There's generally better ways to handle types with kotlinx.serialization though, what are the full datatypes you are working with? Polymorphic serialization may be helpful if you can have type properties in the json.sandwwraith
10/15/2020, 6:56 PMsandwwraith
10/15/2020, 6:57 PMserializer(KType)
works well with Pair, but serializer(j.l.r.Type)
implementation simply lacks one of when
branches. Meanwhile, you do not need to use kotlin-reflect-full or createType
. Take a look at the typeOf<>()
function in stdlibsandwwraith
10/15/2020, 7:00 PMjaqxues
10/15/2020, 7:00 PMsandwwraith
10/15/2020, 7:00 PMKType
should be preferred over j.l.r.Type
since it also saves nullability information (and much easier to create)jaqxues
10/15/2020, 7:01 PMjaqxues
10/15/2020, 7:50 PMsandwwraith
10/16/2020, 2:48 PM