Zhiqiang Bian
11/04/2021, 11:05 PMline 36
: Is it possible to set JsonContentPolymorphicSerializer
for an abstract class programatically in run time? Something looks like
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?Emil Kantis
11/04/2021, 11:11 PM{
"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
@Serializable
data class Person(val name: String, val address: List<String>)
Emil Kantis
11/04/2021, 11:14 PMobject 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
}
)
}
}
Zhiqiang Bian
11/04/2021, 11:39 PMUser
and organisation
, need to be deserialised into.
"User": {
"data": {
"address": [addr1, addr2] => ResourceLink
}
}
"Organisation": {
"data": {
"address": addr3 => ResourceLink
}
}
And my data model is like
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.Zhiqiang Bian
11/04/2021, 11:45 PMJsonContentPolymorphicSerializer
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.