Is there anyway to override the default polymorphic serialization for sealed classes? I’d like to redefine how subclasses are disambiguated.
e
edenman
06/08/2020, 8:26 PM
on a global basis, not that i know of
edenman
06/08/2020, 8:26 PM
on a one-off basis, certainly
edenman
06/08/2020, 8:27 PM
@Serializable(with = MyCustomSerializer::class)
edenman
06/08/2020, 8:28 PM
in my case, the trick with doing custom sealed class deserialization was to decode as a raw JsonObject, then check which class implementation is present, then decode that one
edenman
06/08/2020, 8:29 PM
Copy code
val input =
decoder as? JsonInput ?: throw SerializationException("This class can be loaded only by Json")
val tree =
input.decodeJson() as? JsonObject ?: throw SerializationException("Expected JsonObject")
fieldNameToSerializer.forEach { (name, serializer) ->
if (tree.containsKey(name)) {
return input.json.fromJson(serializer, tree)
}
}
return unknown
edenman
06/08/2020, 8:29 PM
(handling protobuf
oneof
over json where there’s no
type
field, just a “one of these fields will be set” approach)