Kotlin / kotlinx.serialization

Kotlin multiplatform / multi-format serialization
Apache License 2.0
5.38k stars 620 forks source link

Value for serializer ContextDescriptor(...) should always be non-null when trying to serialize null (`Nothing?`) #2828

Open SerVB opened 3 days ago

SerVB commented 3 days ago

Describe the bug

The following code fails in runtime with:

Exception in thread "main" java.lang.IllegalArgumentException: Value for serializer ContextDescriptor(kClass: class java.lang.Object (Kotlin reflection is not available), original: kotlinx.serialization.Polymorphic(type: kotlin.String, value: kotlinx.serialization.Polymorphic<Any>)) should always be non-null. Please report issue to the kotlinx.serialization tracker.
 at kotlinx.serialization.json.internal.StreamingJsonEncoder.encodeSerializableValue (StreamingJsonEncoder.kt:249) 
 at kotlinx.serialization.encoding.AbstractEncoder.encodeSerializableElement (AbstractEncoder.kt:80) 
 at Response$OK.write$Self$web_module (File.kt:7) 

To Reproduce

Playground: https://pl.kotl.in/SHyoGHTDb.

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

@Serializable
sealed interface Response {
    @Serializable
    data class OK<T>(val data: T) : Response
    @Serializable
    data class Error(val error: String) : Response
}

@Serializable
class Payload(val foo: Int)

object Playground {
    @JvmStatic
    fun main(args: Array<String>) {
        println(Json.encodeToString(Response.serializer(), Response.OK(null)))
    }
}

Expected behavior

It's serialized successfully either to {type: ok, data: null} or {type: ok}.

Environment

SerVB commented 2 days ago

So the following additional constructor method solves the problem: https://pl.kotl.in/s13AMnKpB. It's a workaround for me now