Skip to content

Delegate serialization produces incorrect results on Collection elements with polymorphism #2463

@abrooksv

Description

@abrooksv

Describe the bug
When using a custom serializer that is polymorphic on the type argument of a list, the serializer produces an array instead of the expected object

To Reproduce

import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

@Serializable
sealed interface Base

@Serializable
data class GenericError(@SerialName("error_code") val errorCode: Int) : Base

@Serializable
data class Works(val messages: List<Base>)

@Serializable
data class Broken(val messages: List<@Serializable(DelegateSerializer::class) Base>)

object DelegateSerializer : KSerializer<Base> by Base.serializer()

val format = Json { prettyPrint = true }

fun main() {
    /**
     * Produces:
     * {
     *     "messages": [
     *         {
     *             "type": "my.app.GenericError",
     *             "error_code": 404
     *         }
     *     ]
     * }
     */
    println(format.encodeToString(Works(listOf(GenericError(404)))))

    /**
     * Produces:
     * {
     *     "messages": [
     *         ["my.app.GenericError", {
     *                 "error_code": 404
     *             }
     *         ]
     *     ]
     * }
     */
    println(format.encodeToString(Broken(listOf(GenericError(404)))))
}

Expected behavior

Both lines should produce the same output since the delegate serializer should be no-op in this case since everything should be delegated to the generated Base serializer

Environment

  • Kotlin version: 1.9.10
  • Library version: 1.6.0
  • Kotlin platforms: JVM

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