Skip to content

Default polymorphic type handler for deserialization not working for Protobuf #2598

Closed
@ShreckYe

Description

@ShreckYe

Describe the bug

Default polymorphic type handler for deserialization is not working for Protobuf. Originally found while working on #2587 here.

To Reproduce
Attach a code snippet or test data if possible.

Code (adpated from example-poly-19.kt):

@Serializable
abstract class Project {
    abstract val name: String
}

@Serializable
data class NamedProject(@ProtoNumber(1) override val name: String) : Project()

@Serializable
data class BasicProject(@ProtoNumber(1) val type: String, @ProtoNumber(1) override val name: String) : Project()

val module = SerializersModule {
    polymorphic(Project::class) {
        subclass(NamedProject::class)
        defaultDeserializer { BasicProject.serializer() }
    }
}
val json = Json { serializersModule = module }
val protoBuf = ProtoBuf { serializersModule = module }

@OptIn(ExperimentalStdlibApi::class)
fun main() {
    fun decodeProjectTest(serialName: String) {
        println(json.decodeFromString<Project>("""{"type":"$serialName","name":"test"}"""))

        val serializedNameMessageString = "12" + "06" + "0a" + "04" + "test".encodeToByteArray().toHexString()
        println(
            protoBuf.decodeFromHexString<Project>(
                "0a" +
                    serialName.length.toByte().toHexString() +
                    serialName.encodeToByteArray().toHexString() +
                    serializedNameMessageString
            )
        )
    }
    decodeProjectTest(NamedProject.serializer().descriptor.serialName)
    decodeProjectTest("NotRegisteredProject")
}

Output:

NamedProject(name=test)
NamedProject(name=test)
BasicProject(type=NotRegisteredProject, name=test)
Exception in thread "main" kotlinx.serialization.MissingFieldException: Field 'type' is required for type with serial name 'example.examplePoly19.BasicProject', but it was missing

Expected behavior

Environment

Commit 1f7372a of this project.

  • Kotlin version: [e.g. 1.9.22]
  • Library version: [e.g. 1.6.4-SNAPSHOT]
  • Kotlin platforms: [e.g. JVM]
  • Gradle version: [e.g. 7.6.1]
  • IDE version (if bug is related to the IDE) [e.g. IntelliJ IDEA 2023.3.4 (Community Edition)]
  • Other relevant context [OS version Ubuntu 22.04.4 LTS, JRE version 17]

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions