Arkadii Ivanov
10/25/2023, 8:49 PMKSerializer
is correct. See the thread. It seems working but I want to double check.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)
}
PolymorphicSerializer
as follows.
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
}