Skip to content

polymorphicDefaultDeserializer won't work with useArrayPolymorphism=true #3015

Open
@Komdosh

Description

@Komdosh

Describe the bug

polymorphicDefaultDeserializer won't work with useArrayPolymorphism=true

To Reproduce

public fun main() {
    val arrayPolymorphism = true
    val json = Json {
        serializersModule = SerializersModule {
            useArrayPolymorphism = arrayPolymorphism
            polymorphicDefaultDeserializer(ChildWithPoly::class) { ChildWithPoly.ChildLegacy.serializer() }
        }
    }
    val obj = Parent(ChildWithPoly.ChildLegacy("Hello World!"))

    println(json.encodeToString(Parent.serializer(), obj))

    if (arrayPolymorphism) {
        val parentWithType = json.decodeFromString<Parent>("""{"child":["ChildLegacy",{"s":"Hello World!"}]}""")
        println(obj == parentWithType)
    } else {
        val parentWithType = json.decodeFromString<Parent>("""{"child":{"type":"ChildLegacy", "s":"Hello World!"}}""")
        println(obj == parentWithType)
    }

    val parentWithoutType = json.decodeFromString<Parent>("""{"child":{"s":"Hello World!"}}""")
    println(obj == parentWithoutType) // fail if arrayPolymorphism == true
}

@Serializable
public data class Parent(
    val child: ChildWithPoly,
)

@Serializable
public sealed interface ChildWithPoly {

    @Serializable
    @SerialName("ChildLegacy")
    public data class ChildLegacy(
        val s: String,
    ) : ChildWithPoly

    @Serializable
    @SerialName("ChildNew")
    public data class ChildNew(
        val s: String,
    ) : ChildWithPoly
}

Expected behavior

polymorphicDefaultDeserializer works with useArrayPolymorphism

Environment

  • Kotlin version: 2.1.21
  • Library version: 1.8.1
  • Kotlin platforms: JVM, JS
  • Gradle version: 8.14.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions