Is it possible to do polymorphic serialization bas...
# serialization
k
Is it possible to do polymorphic serialization based on the presence or absence of a field? I want to have the following hierarchy for a DB entity
Copy code
sealed interface Entity {
  val commonProperty: Int

  class New(override val commonProperty: Int) : Entity
  class Persisted(
    val id: Long,
    override val commonProperty: Int
  ) : Entity
}
Given the following json
Copy code
[
  { "commonProperty": 0 },
  { "id": 1, "commonProperty": 0 }
]
I would like that to deserialize to the following in Kotlin
Copy code
[New(commonProperty = 0), Persisted(id = 1, commonProperty = 0)]
I realize a more simple model could look like the following:
Copy code
class Entity(val id: Long?, val commonProperty: Int)
but that would require either passing in
null
explcitily in JSON, or disabling
Json.explicitNulls
globally which I'd like to avoid.
z
You could set a default parameter value for
id
Kotlinx serialization would then deserialize to that value if it's missing in the input
a
yes, you can create a
JsonContentPolymorphicSerializer
that can check if a JSON property is present or missing, and then select the serializer you’d like to use https://github.com/Kotlin/kotlinx.serialization/blob/v1.4.1/docs/json.md#content-based-polymorphic-deserialization
k
@Adam S I don't know how I didn't see this in the docs! This is fantastic. Thank you.
103 Views