Hi guys! I'm currently migrating from Moshi to kot...
# serialization
j
Hi guys! I'm currently migrating from Moshi to kotlin Serialization and was wondering if there is an easier solution for a polymorphic issue I'm facing. For the following:
Copy code
sealed interface Animal {
    val type: String
}
data class Cat(override val type: String) : Animal
data class Dog(override val type: String) : Animal
If I wanted to deserialize different "type values" into the same class, using moshi it would be a simple:
Copy code
internal object AnimalJsonAdapter : JsonAdapter.Factory by PolymorphicJsonAdapterFactory
    .of(Animal::class.java, "type")
    .withSubtype(Cat::class.java, "cat")
    .withSubtype(Dog::class.java, "labradoodle")
    .withSubtype(Dog::class.java, "greyhound")
To achieve the same, using serialization, I could only find this approach:
Copy code
@Serializable
sealed interface Dog : Animal

@SerialName("labradoodle")
@Serializable
data class Labradoodle(override val type: String) : Dog

@SerialName("greyhound")
@Serializable
data class Greyhound(override val type: String) : Dog
But this results in a lot of duplicated classes if I have multiple possible types. Does any one know of a better solution?
e
I don't think there's any built-in way to handle that, but you might be able to register a polymorphicDefaultSerializer which maps the additional names
j
I took a look at that... But I couldn't find a way to provide multiple names
e
j
That's great, thank you! I wasn't understanding that the lambda returned the
type
🙏
a
@ephemient thank you for showing off how the playground may be used for communication