SealedClassSerializer
This class provides support for multiplatform polymorphic serialization of sealed classes.
In contrary to PolymorphicSerializer, all known subclasses with serializers must be passed in subclasses
and subSerializers
constructor parameters. If a subclass is a sealed class itself, all its subclasses are registered as well.
If a sealed hierarchy is marked with @Serializable, an instance of this class is provided automatically. In most of the cases, you won't need to perform any manual setup:
@Serializable
sealed class SimpleSealed {
@Serializable
public data class SubSealedA(val s: String) : SimpleSealed()
@Serializable
public data class SubSealedB(val i: Int) : SimpleSealed()
}
// will perform correct polymorphic serialization and deserialization:
Json.encodeToString(SimpleSealed.serializer(), SubSealedA("foo"))
However, it is possible to register additional subclasses using regular SerializersModule. It is required when one of the subclasses is an abstract class itself:
@Serializable
sealed class ProtocolWithAbstractClass {
@Serializable
abstract class Message : ProtocolWithAbstractClass() {
@Serializable
data class StringMessage(val description: String, val message: String) : Message()
@Serializable
data class IntMessage(val description: String, val message: Int) : Message()
}
@Serializable
data class ErrorMessage(val error: String) : ProtocolWithAbstractClass()
}
In this case, ErrorMessage
would be registered automatically by the plugin, but StringMessage
and IntMessage
require manual registration, as described in PolymorphicSerializer documentation:
val abstractContext = SerializersModule {
polymorphic(ProtocolWithAbstractClass::class) {
subclass(ProtocolWithAbstractClass.Message.IntMessage::class)
subclass(ProtocolWithAbstractClass.Message.StringMessage::class)
// no need to register ProtocolWithAbstractClass.ErrorMessage
}
}
Properties
Describes the structure of the serializable representation of T, produced by this serializer. Knowing the structure of the descriptor is required to determine the shape of the serialized form (e.g. what elements are encoded as lists and what as primitives) along with its metadata such as alternative names.
Returns a nullable serializer for the given serializer of non-null type.
Functions
Deserializes the value of type T using the format that is represented by the given decoder. deserialize method is format-agnostic and operates with a high-level structured Decoder API. As long as most of the formats imply an arbitrary order of properties, deserializer should be able to decode these properties in an arbitrary order and in a format-agnostic way. For that purposes, CompositeDecoder.decodeElementIndex-based loop is used: decoder firstly signals property at which index it is ready to decode and then expects caller to decode property with the given index.
Lookups an actual serializer for given klassName withing the current base class. May use context from the decoder.