Is there anyway to override the default polymorphi...
# serialization
s
Is there anyway to override the default polymorphic serialization for sealed classes? I’d like to redefine how subclasses are disambiguated.
e
on a global basis, not that i know of
on a one-off basis, certainly
@Serializable(with = MyCustomSerializer::class)
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
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
(handling protobuf
oneof
over json where there’s no
type
field, just a “one of these fields will be set” approach)
s
Gotcha, thanks
👍 1