Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Kotlin コルーチン
/ /

Kotlin 直列化

Kotlin ドライバーは、 Kotlin オブジェクトを直列化および逆直列化するための kotlinx.serializationライブラリをサポートしています。

このドライバーは効率的なBsonシリアライザーを提供し、 @Serializableとしてマークされたクラスで使用して、 Kotlin オブジェクトの BSON データへの直列化を処理します。

また、 bson-kotlinxライブラリをインストールして、デフォルトのエンコード、null のエンコード、クラス弁別子を定義する構成でカスタム コーデックをサポートすることもできます。

注意

Kotlin シリアル化ライブラリではなくCodecインターフェースを使用して Kotlin オブジェクトを BSON データにカスタム エンコードおよびデコードを指定する方法については、「 コーデックガイド」を参照してください。

フレームワークにすでに理解している場合、または慣用的な Kotlin アプローチを使用したい場合は、 Kotlin シリアル化を選択することができます 。

Kotlin ドライバーは Kotlin シリアル化Jsonライブラリで使用できますが、 JsonシリアライザーはObjectIdなどの BSON 値型を直接サポートしていませ。 BSON と JSON の間の変換を処理できるカスタム シリアライザーを提供する必要があります。

Kotlin ドライバーは次の機能をサポートします。

  • Kotlin 直列化ライブラリでサポートされているすべての Kotlin 型

  • 利用可能なすべてのBSON types

Support for serialization in the Kotlin driver depends on the official Kotlin serialization library.

GradleMavenパッケージ マネージャーを使用してプロジェクトにシリアル化の依存関係を追加する方法を確認するには、次のタブから選択します。

Gradle を使用して依存関係を管理している場合は、次のものをbuild.gradle.kts 依存関係リストに追加します。

build. Gradle.kts
implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:1.6.0")
implementation("org.mongodb:bson-kotlinx:5.0.0")

Maven を使用して依存関係を管理している場合は、次のものをpom.xml 依存関係リストに追加します。

pom.xml
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-serialization-core</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>bson-kotlinx</artifactId>
<version>5.0.0</version>
</dependency>

クラスをシリアル化可能として宣言するには、 Kotlin シリアル化フレームワークからの@Serializableアノテーションで Kotlin データクラスを注釈を付けます。

データ クラスは、シリアル化可能としてマークすると、コード内で通常どおり使用できます。 Kotlin ドライバーと Kotlin 直列化フレームワークは BSON の直列化と逆直列化を処理します。

この例では、次の注釈が付けられた単純なデータ クラスを示しています。

  • @Serializable クラスをシリアル化可能なものとしてマークします。

  • @SerialName で、BSON ドキュメント内の プロパティと プロパティの名前を指定します。idmanufacturerこれは、シリアル化可能なクラスでサポートされていない@BsonId@BsonPropertyアノテーションの代わりに使用できます。

  • @Contextual BSON idプロパティをマークし、組み込みのObjectIdSerializerを使用します。 この注釈は、BSON types を正しく直列化するのに必要です。

@Serializable
data class PaintOrder(
@SerialName("_id") // Use instead of @BsonId
@Contextual val id: ObjectId?,
val color: String,
val qty: Int,
@SerialName("brand")
val manufacturer: String = "Acme" // Use instead of @BsonProperty
)

注意

@Serializableデータクラスではorg.bson.codecs.pojo.annotationsパッケージの注釈は使用できません。

For more information on serializable classes and available annotation classes, see the official Kotlin Serialization documentation.

BSON でのデータの表現方法を処理するカスタム シリアライザーを作成できます。 Kotlin ドライバーは、 kotlinx.serializationパッケージのKSerializerインターフェースを使用してカスタム シリアライザーを実装します。 特定のフィールドの@Serializableアノテーションのパラメータとしてカスタム シリアライザーを指定できます。

次の例は、カスタムKSerializerインスタンスを作成して、 kotlinx.datetime.InstantBsonDateTimeに変換する方法を示しています。

object InstantAsBsonDateTime : KSerializer<Instant> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("InstantAsBsonDateTime", PrimitiveKind.LONG)
override fun serialize(encoder: Encoder, value: Instant) {
when (encoder) {
is BsonEncoder -> encoder.encodeBsonValue(BsonDateTime(value.toEpochMilliseconds()))
else -> throw SerializationException("Instant is not supported by ${encoder::class}")
}
}
override fun deserialize(decoder: Decoder): Instant {
return when (decoder) {
is BsonDecoder -> Instant.fromEpochMilliseconds(decoder.decodeBsonValue().asDateTime().value)
else -> throw SerializationException("Instant is not supported by ${decoder::class}")
}
}
}

次のコードは、 orderDateフィールドが、前のコードで定義されたカスタム シリアライザー クラスを指定する注釈を持つPaintOrderデータクラスを示しています。

@Serializable
data class PaintOrder(
val color: String,
val qty: Int,
@Serializable(with = InstantAsBsonDateTime::class)
val orderDate: Instant,
)

このセクションで説明されるメソッドとクラスの詳細については、次の API ドキュメントを参照してください。

org.bson.codecs.kotlinxパッケージのKotlinSerializerCodecクラスを使用して、 @Serializableデータ クラスのコーデックを作成し、保存する内容をカスタマイズできます。

BsonConfigurationクラスを使用して、デフォルトをエンコードするか、null をエンコードするか、クラス弁別子を定義するかなどの構成を定義します。

カスタム コーデックを作成するには、プロジェクトにbson-kotlinx依存関係をインストールします。 GradleMavenパッケージ マネージャーを使用してプロジェクトに依存関係を追加する方法を確認するには、次のタブから を選択します。

Gradle を使用して依存関係を管理している場合は、次のものをbuild.gradle.kts 依存関係リストに追加します。

build. Gradle.kts
implementation("org.mongodb:bson-kotlinx:5.0.0")

Maven を使用して依存関係を管理している場合は、次のものをpom.xml 依存関係リストに追加します。

pom.xml
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>bson-kotlinx</artifactId>
<version>5.0.0</version>
</dependency>

注意

bson-kotlin 依存関係

オプションで、デフォルトのコーデック レジストリを使用して bson-kotlin 依存関係をインストールすることもできます。この依存関係はリフレクションとコーデック レジストリを使用してKotlinデータ クラスをサポートしていますが、BsonDiscriminatorBsonExtraElementsBsonConstructor などの特定の POJO 注釈はサポートされていません。詳細については、bson-kotlin APIドキュメント を参照してください。

一般的に、コーデック構成には高速なbson-kotlinxライブラリをインストールして使用することをお勧めします。

Then, you can define your codec using the KotlinSerializerCodec.create() method and add it to the registry.

次の例は、 KotlinSerializerCodec.create()メソッドを使用してコーデックを作成し、デフォルトをエンコードしないように構成する方法を示しています。

import org.bson.codecs.configuration.CodecRegistries
import org.bson.codecs.kotlinx.BsonConfiguration
import org.bson.codecs.kotlinx.KotlinSerializerCodec
val myCustomCodec = KotlinSerializerCodec.create<PaintOrder>(
bsonConfiguration = BsonConfiguration(encodeDefaults = false)
)
val registry = CodecRegistries.fromRegistries(
CodecRegistries.fromCodecs(myCustomCodec), collection.codecRegistry
)

このセクションで説明されるメソッドとクラスの詳細については、次の API ドキュメントを参照してください。

戻る

ドキュメント

項目一覧