https://kotlinlang.org logo
#serialization
Title
# serialization
a

Arkadii Ivanov

10/25/2023, 8:49 PM
I'm playing with polymorphic serialization but with a tricky use case. Wondering whether the following implementation of
KSerializer
is correct. See the thread. It seems working but I want to double check.
Untitled.kt
Let's say there is a library that I don't own, which contains the following code.
Copy code
interface Some

// Some storage, unrelated to the question
internal var storedJson: String? = null

fun <T : Any> save(value: T, serializationStrategy: SerializationStrategy<T>) {
    val json = Json.encodeToString(serializer = serializationStrategy, value = value)
    storedJson = json
}

fun <T : Any> restore(deserializationStrategy: DeserializationStrategy<T>): T? {
    val json = storedJson ?: return null
    return Json.decodeFromString(deserializer = deserializationStrategy, string = json)
}
And I want to use that
PolymorphicSerializer
as follows.
Copy code
class FooTest {

    @Test
    fun foo() {
        val value = Value(some = SomeImpl(value = 1))

        save(value, Value.serializer())
        val restoredValue = restore(Value.serializer())

        assertEquals(value, restoredValue)
    }

    @Serializable
    data class Value(
        @Serializable(SomeSerializer::class) val some: Some,
    )

    object SomeSerializer : PolymorphicSerializer<Some>(
        baseClass = Some::class,
        module = SerializersModule {
            polymorphic(Some::class) {
                subclass(SomeImpl::class, SomeImpl.serializer())
            }
        },
    )

    @Serializable
    data class SomeImpl(val value: Int) : Some
}
The test passes, though I'm not sure if it's OK that it's not possible to introspect my `PolymorphicSerializer`'s descriptor, as it contains a contextual element and the module is not registered anywhere.