Thanks to visit codestin.com
Credit goes to github.com

Skip to content

coerceInputValues=true and explicitNulls=false should decode unknown enum value without default to null #2586

@carstenhag

Description

@carstenhag

Describe the bug
We updated from 1.6.2 to 1.6.3 and now nullable enums without explicit null default don't get decoded anymore, leading to an exception.

To Reproduce

val json = Json {
    ignoreUnknownKeys = true
    isLenient = true
    coerceInputValues = true
    explicitNulls = false
}

@Serializable
data class Outer(
    @SerialName("service")
    val service: Service?,
)

@Serializable
enum class Service {
    @SerialName("card")
    CARD,
}

val serviceJson = """{"service":"test"}"""
json.decodeFromString<Outer>(serviceJson)

SerializationException: org.example.Service does not contain element with name 'test' at path $.service

Expected behavior
We were expecting that these configs (taken from the documentation) get "added up" together:

  • coerceInputValues = true:
    • Enables coercing incorrect JSON values to the default property value in the following cases:
    • Property type is an enum type, but JSON value contains unknown enum member
  • explicitNulls = false:
    • When this flag is disabled [...] during decoding, the absence of a field value is treated as null for nullable properties without a default value.

In other words: For a nullable enum without default value, set its value to "null" if the JSON value is an unknown enum member.

Other
Apart from combining these two config properties, I wouldn't know how we can get automatic nulls? We would have to set an explicit null to each nullable enum?
Also see #2585.

Environment

  • Kotlin version: 1.9.22
  • Library version: Bug introduced in 1.6.3, working in 1.6.2
  • Kotlin platforms: JVM
  • Gradle version: 8.6
  • Other relevant context: OpenJDK 21.0.2

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions