CodexBloom - Programming Q&A Platform

Kotlin Serialization: advanced patterns with Nested Data Classes and Polymorphism in Kotlin 1.8

πŸ‘€ Views: 75 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-15
kotlin serialization kotlinx.serialization polymorphism Kotlin

I'm working with an scenario with Kotlin serialization when trying to serialize and deserialize nested data classes that include polymorphic types. I'm using Kotlin 1.8 along with the kotlinx.serialization library (version 1.4.0). I've defined a base class and a couple of subclasses, but when I attempt to deserialize a JSON string, I'm getting an `Invalid type descriptor` behavior. Here’s a simplified version of my code: ```kotlin import kotlinx.serialization.* import kotlinx.serialization.json.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* @Serializable sealed class Shape @Serializable @SerialName("Circle") data class Circle(val radius: Double) : Shape() @Serializable @SerialName("Square") data class Square(val side: Double) : Shape() @Serializable data class Canvas(val shapes: List<Shape>) fun main() { val jsonString = "{"shapes":[{"type":"Circle","radius":5.0},{"type":"Square","side":10.0}]}" val canvas = Json.decodeFromString<Canvas>(jsonString) } ``` In the JSON string, I'm trying to specify types for the nested objects, but it seems my approach isn't working as intended. I've also tried to define a custom serializer for the `Shape` class, but that led to more errors regarding the type handling. The behavior message states: `Invalid type descriptor: Expected a class, but found a primitive or non-serializable type`. I ensured that the `@Serializable` annotations are correctly placed, and all classes have default constructors. What am I missing here? Is there a specific way to handle polymorphic serialization with nested classes in Kotlin? Any help would be greatly appreciated!