Skip to content

Default serializer for sealed types if input has no explicit type #902

@charleskorn

Description

@charleskorn

What is your use-case and why do you need this feature?

Let's say I have some JSON that looks like this:

{ "type": "typeA", "option": "abc123" }

or

{ "type": "typeB", "otherOption": 15 }

I can use a sealed type to represent these types in Kotlin, and deserialize the JSON into objects without any issues.

However, what I would like to be able to do is default to a particular type if there is no type in the JSON input. For example, if { "option": "abc123" } was the input, I'd like to default to treating that as if it was a typeA.

Describe the solution you'd like
Perhaps this could be done with an annotation on the base class?

For example:

@PolymorphicDefault(TypeA::class)
sealed class Options

data class TypeA(val option: String) : Options
data class TypeB(val otherOption: Int) : Options

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions