João Silva
12/04/2025, 11:56 AMsealed 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:
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:
@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?ephemient
12/04/2025, 2:02 PMJoão Silva
12/04/2025, 2:07 PMephemient
12/04/2025, 2:58 PMJoão Silva
12/04/2025, 3:20 PMtype 🙏AndreyVanDenHaag
12/05/2025, 11:27 AM