Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unexpected MissingFieldException when decoding explicit null value from json for nullable enum #2170

Closed
ryanholden8 opened this issue Jan 26, 2023 · 0 comments
Assignees

Comments

@ryanholden8
Copy link

ryanholden8 commented Jan 26, 2023

Describe the bug
When a property is set to null in the json and the model property is nullable, parsing the property to null should always work.
No coercing or leniency is needed since it directly maps accurately to the model.

However, setting isLenient OR coerceInputValues to true causes an unexpected MissingFieldException even though the field is clearly and accurately defined in the json.

To Reproduce

This test will unexpectedly fail with a thrown MissingFieldException:

import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import org.junit.Test

class SerializationTest {

    @Test
    fun `model with nullable enum and explicit json null value does not throw MissingFieldException`() {
        // Arrange: Json with a valid null value
        val jsonWithExplicitNullValue = """
            {
                "color": null
            }
        """.trimIndent()

        // Arrange: Serializer that is as forgiving as possible
        val jsonSerializerLenient = Json {
            isLenient = true // NOTE: Test will pass if this is false
            coerceInputValues = true // NOTE: OR test will pass if `isLenient` is true and this is false
            ignoreUnknownKeys = true
            prettyPrint = true
            allowStructuredMapKeys = true
        }

        // Act: Convert json to model
        val model = jsonSerializerLenient.decodeFromString<Model>(jsonWithExplicitNullValue)

        // Assert: Model converted and value is null like in the json
        assert(model.color == null)
    }

    @Serializable
    data class Model(
        val color: Color?
    )

    enum class Color {
        Red,
        Blue,
        Green
    }
}

Expected behavior

Environment

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants