Skip to content

Properties inherit from parent class which use custom serializer not serialized #1043

Closed as not planned
@rwsbillyang

Description

@rwsbillyang

Describe the bug
The properties inherit from parent class are not serialized if parent class use custom serializer.

To Reproduce
If use default serializer generated by plugin, works fine:

{"msg":null,"code":0}
{"msg":null,"code":0,"content":"some content"}

If use custom serializer, derived class lack of properties from base class:

{"msg8":null,"msg8":0} //works fine
{"content":"some content"} //Expect: {"msg8":null,"code8":0,"content":"some content"}

The test code:

@Serializable(with = Box8Serializer::class)
//@Serializable
open class Box8 { //if use sealed instead of open, same result
    var msg: String? = null
    var code: Int = 0
}

// if put properties of parent class in its constructor reports:
//Impossible to make this class serializable because its parent is not serializable and does not have exactly one constructor without parameters
@Serializable
class TheTextMsg(val content: String) : Box8()

fun testCustomSerializerAndInheritance() {
    val box = Box8()
    val textMsg = TheTextMsg("some content")
    val json = Json {
         // same result
//        serializersModule = SerializersModule {
//            polymorphic(Box8::class) {
//                subclass(TheTextMsg::class)
//            }
//        }
    }

    println(json.encodeToString(box))
    println(json.encodeToString(textMsg))

    // if parent class use serializer generated by plugin
    //{"msg":null,"code":0}
    //{"msg":null,"code":0,"content":"some content"}

    //if use custom serializer, output:
    //{"msg8":null,"msg8":0}
    //{"content":"some content"}
}


object Box8Serializer : KSerializer<Box8> {
    override val descriptor: SerialDescriptor =
            buildClassSerialDescriptor("box") {
                element<String?>("msg8", isOptional = true)
                element<Int?>("code8", isOptional = true)
            }

    @ExperimentalSerializationApi
    override fun serialize(encoder: Encoder, value: Box8) =
            encoder.encodeStructure(descriptor) {
                encodeNullableSerializableElement(descriptor, 0, String.serializer(), value.msg)
                encodeIntElement(descriptor, 1, value.code)
            }

    override fun deserialize(decoder: Decoder): Box8 {
        TODO("Not implement")
    }
}

Expected behavior
using custom serializer when serialize

Environment

  • Kotlin version: 1.4.0
  • Library version: 1.0.0-RC
  • Kotlin platforms: JVM
  • Gradle version: 6.3
  • IDE version: IntellijIDEA 2020.2.1
  • Other relevant context : MacOS 10.12.6, JDK 1.8.0_261

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