While this guide covers a lot of useful examples for polymorphic classes serialization, I couldn’t find any information about one particular (and to my mind, very useful) case.
Serialization of open classes and their children is definitely allowed, so it would be just very logical to allow overriden properties for these child classes. Consider following example:
import kotlinx.serialization.*
import kotlinx.serialization.json.*
import kotlinx.serialization.modules.*
val module = SerializersModule {
polymorphic(Project::class) {
subclass(OwnedProject::class)
}
}
val format = Json { serializersModule = module }
@Serializable
open class Project {
open var name: String = "project"
}
@Serializable
@SerialName("Owned")
class OwnedProject(val owner: String) : Project() {
override var name: String = "ownedProject"
}
fun main() {
val data: Project = OwnedProject("kotlin")
println(format.encodeToString(data))
}
It could be nice if I could for example deserialize both Project
and OwnedProject
and if name
key wasn’t present in input, get it set to “project” and “ownedProject” respectively (the default value).
But now I can get only Serializable class has duplicate serial name of property 'name', either in the class itself or its supertypes
error, and that makes me not very optimistic. Maybe I skipped something and there is a way to achieve this?