Skip to content

KSerializer.serialize() of nullable type not invoked for null values #824

@koral--

Description

@koral--

In the project's code there is a nullable value.
Magic not null values need to be deserialized to null.
And nulls need to be serialized to non-null magic values.

While I'm able to deserialize to nulls the serialization does not work. serialize() method is not fired and null is passed to serialized form.

To Reproduce
Serializer code:

internal object LocalTimeSerializer : KSerializer<LocalTime?> {

    override val descriptor = PrimitiveDescriptor("LocalTime?", PrimitiveKind.INT)

    override fun deserialize(decoder: Decoder): LocalTime? = when (val seconds = decoder.decodeInt()) {
       -1 -> null
        else -> LocalTime.ofSecondOfDay(seconds.toLong())
    }

    override fun serialize(encoder: Encoder, value: LocalTime?) {
        when (value) {
            null -> encoder.encodeInt(-1) //this line is never reached despite that nulls exist in serialized lists
            else -> encoder.encodeInt(value.toSecondOfDay())
        }
    }
}

Usage inside serializable class:

val times: List<@Serializable(with = LocalTimeSerializer::class) LocalTime?>,

Expected behavior
serialize() method is invoked for nulls.

Environment

  • Kotlin version: 1.3.72
  • Library version: 0.20.0
  • Kotlin platforms: JVM
  • Gradle version: 6.3+

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions