Skip to content

Deserialize null/missing fields to empty collections with default values #3119

@jpilch

Description

@jpilch

What is your use-case and why do you need this feature?
I would like to deserialize JSON where a collection field can be null, missing, or an empty array, and have all three cases result in an empty collection in the deserialized object.

Describe the solution you'd like
With the following data class:

@Serializable
data class MyDto(
  val name: String,
  val items: List<String>
)

I'd like for all three JSON inputs to successfully deserialize with items as an empty list:

val json = Json {}

// All three should work:
json.decodeFromString<MyDto>("""{"name":"test","items":[]}""")
json.decodeFromString<MyDto>("""{"name":"test","items":null}""")
json.decodeFromString<MyDto>("""{"name":"test"}""")

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions