kotlinx.serialization icon indicating copy to clipboard operation
kotlinx.serialization copied to clipboard

Unable to deserialize sealed interface with value class children

Open Nek-12 opened this issue 1 year ago • 0 comments

This code is impossible to deserialize:

@Serializable
data class EditPromoCodeRequest(
    val code: String? = null,
    val owner: UserQuery? = null,
) 

@Serializable
sealed interface UserQuery {

    @Serializable
    @SerialName("id")
    @JvmInline
    value class Id(val id: UUID) : UserQuery

    @Serializable
    @SerialName("email")
    @JvmInline
    value class Email(val email: String) : UserQuery
}

When a json object is sent, the serialization fails with :

Illegal input: Unexpected JSON token at offset 54: Expected beginning of the string, but got { at path: $.owner

When a string is sent, the request fails with:

Illegal input: Expected JsonObject, but had JsonLiteral as the serialized body of UserQuery at element: $.owner

Example of a correct body:

{
    "owner": {
        "type": "email",
        "email": "[email protected]"
    }
}

Environment

  • Kotlin version: 2.0.20
  • Library version: [e.g. 0.11.0] 1.7.3
  • Kotlin platforms: [e.g. JVM, JS, Native or their combinations] JVM backend
  • Gradle version: [e.g. 4.10] 8.10

Nek-12 avatar Oct 14 '24 12:10 Nek-12