Hello, I previously used Gson and used the "Type" ...
# serialization
j
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.
Copy code
@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
Copy code
class Data {
    // Allow KClass for simpler JsonElements to be deserialized
    val type: Either<KClass<*>, KType<*>>

    fun deserialize() { ... }
}
r
You could store `KSerializer<T>`'s instead of type tokens/ktypes and use them the same way (as the first parameter to
decodeFromString
). 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.
s
That's actually a slight overlook in an implementation
serializer(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 stdlib
j
Alright, thanks!
s
Anyway,
KType
should be preferred over
j.l.r.Type
since it also saves nullability information (and much easier to create)
j
yes i am working on nullability support
One last question: Does it even make sense to want to store a simple type as KClass, or does it not matter if I have everything as KType (regarding space efficiency).
s
I do not think that KType is much 'heavier' than KClass