Hi, I have two separate questions on Polymorphic S...
# serialization
z
Hi, I have two separate questions on Polymorphic Serializer. •
line 36
: Is it possible to set
JsonContentPolymorphicSerializer
for an abstract class programatically in run time? Something looks like
Copy code
AbstractRelationship.serializer = if (flag == 1) polySerializer1 else polySerializer2
• I am deserialising
AbstractRelationship
based on the JsonElement inside. Is it possible to make polymorphic based on the map key on
line 32
, maybe with Contextual Serializer or Map Serializer?
e
To me it looks like you have an entity that contains either a single reference, or a list of references? Like :
Copy code
{
  "name": "John"
  "address": "my address"
}

{
  "name": "Emmanouil",
  "address": ["addr1", "addr2"]
}
If so, you could use a
JsonTransformingSerializer
to always wrap potential single elements before delegating to a generated serializer for
Copy code
@Serializable
data class Person(val name: String, val address: List<String>)
Something like..
Copy code
object PersonSerializer : JsonTransformingSerializer<Person>(Person.serializer()) {

   override fun transformDeserialize(element: JsonElement): JsonElement {
      if (element !is JsonObject) return element
      return JsonObject(
         element.jsonObject.entries.associate { (key, value) ->
            if (key == "address" && value !is JsonArray) key to JsonArray(listOf(value)) 
            else key to value
         }
      )
   }
}
z
My use case is like having a dynamic PolyphomicSerializer. Assume there are two different class,
User
and
organisation
, need to be deserialised into.
Copy code
"User": {
    "data": {
        "address": [addr1, addr2] => ResourceLink
    }
}

"Organisation": {
    "data": {
        "address": addr3 => ResourceLink
    }
}
And my data model is like
Copy code
class User(val address: List<Address>)
class Organisation(val address: Address)
You told me about
JsonTransformingSerializer
a few days ago, and it is a good workaround for me. (And thank you for answering my question again🙏). I just need to turn the
address
of
organisation
into a list with one item inside. Now, I am trying to find out if I can preserve the difference of
T
and
List<T>
in my models.
So, setting
JsonContentPolymorphicSerializer
dynamically in run-time would be the ideal solution for me (if it is doable). Alternatively, I can just keep using my current SingleItemList Strategy, which also works but not ideal, because it twists the models.