https://kotlinlang.org logo
#serialization
Title
# serialization
s

Shivam Verma

03/10/2023, 4:39 PM
Hi folks, I am experiencing a weird behavior when decoding a nullable enum property. When trying out "json string -> json element -> decode", the decoder fails to parse the object complaining about missing element in json. However, when trying "json string -> decode" the parsing works as expected. Test in 🧵
Copy code
package com.n26.insights

import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.decodeFromJsonElement
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals

class InfoCardRawTest {

    @Serializable
    sealed class Card {
        abstract val theme: Theme?
    }

    @Serializable
    enum class Theme {
        @SerialName("dark")
        DARK,

        @SerialName("light")
        LIGHT
    }

    @Serializable
    @SerialName("card")
    data class InfoCard(
        val type: String,
        val title: String?,
        override val theme: Theme?
    ) : Card()

    @OptIn(ExperimentalSerializationApi::class)
    val json = Json {
        coerceInputValues = true
        explicitNulls = false
    }

    private val raw = """
        {
            "type": "card"
        }
    """.trimIndent()

    @Test
    // This one fails
    fun verifyDecodingFromJsonElement() {
        assertEquals(
            json.decodeFromJsonElement(json.parseToJsonElement(raw)),
            InfoCard(
                type = "card",
                title = null,
                theme = null
            )
        )
    }

    @Test
    // This one passes
    fun verifyDecodingFromJsonString() {
        assertEquals(
            json.decodeFromString(raw), InfoCard(
                type = "card",
                title = null,
                theme = null
            )
        )
    }
}
10 Views