InstantAsBsonDatetimeSerializer

Serializer for kotlin.time.Instant that serializes as a BsonType.Datetime.

The MongoDB official driver's KotlinX.Serialization support doesn't yet support kotlin.time.Instant (see JAVA-6084). This serializer adds this support. Once this ticket is fixed, this serializer will be deprecated.

When KtMongo Multiplatform's BSON implementation is used, this serializer does nothing, as the default serializer already uses BsonType.Datetime.

Behavior with non-BSON formats

When serializing to non-BSON formats (e.g., JSON, gRPC…), the instant is encoded as a string in ISO-8601 format.

Example

The annotation UseSerializers can be used to configure all Instant fields in that file to use this serializer:

@file:UseSerializers(InstantAsBsonDatetimeSerializer::class)

@Serializable
data class Foo(
val _id: ObjectId,
val createdAt: Instant,
)

Alternatively, Serializable can be used to configure a specific Instant field to use this serializer:

@Serializable
data class Foo(
val _id: ObjectId,
val createdAt: @Serializable(with = InstantAsBsonDatetimeSerializer::class) Instant,
)

Properties

Link copied to clipboard
open override val descriptor: SerialDescriptor

Functions

Link copied to clipboard
open override fun deserialize(decoder: Decoder): Instant
Link copied to clipboard
open override fun serialize(encoder: Encoder, value: Instant)