ContextualSerializer
This class provides support for retrieving a serializer in runtime, instead of using the one precompiled by the serialization plugin. This serializer is enabled by Contextual or UseContextualSerialization.
Typical usage of ContextualSerializer
would be a serialization of a class which does not have static serializer (e.g. Java class or class from 3rd party library); or desire to override serialized class form in one dedicated output format.
Serializers are being looked for in a SerializersModule from the target Encoder or Decoder, using statically known KClass. To create a serial module, use SerializersModule factory function. To pass it to encoder and decoder, refer to particular SerialFormat's documentation.
Usage of contextual serializer can be demonstrated by the following example:
import java.util.Date
@Serializable
class ClassWithDate(val data: String, @Contextual val timestamp: Date)
val moduleForDate = serializersModuleOf(MyISO8601DateSerializer)
val json = Json { serializersModule = moduleForDate }
json.encodeToString(ClassWithDate("foo", Date())
If type of the property marked with @Contextual
is @Serializable
by itself, the plugin-generated serializer is used as a fallback if no serializers associated with a given type is registered in the module. The fallback serializer is determined by the static type of the property, not by its actual type.
Constructors
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.