0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ZIO Schema: 1つのスキーマ定義でJSONとAvro形式を切り替える

Posted at

はじめに

ZIO Schemaを使用すると、一度データ構造をSchemaとして定義するだけで、
JSONやバイナリ形式など、データを様々な形式へ変換することができます。

本記事では、ZIO Schemaを用いて、ケースクラスをJSONとAvroバイナリ形式に変換する例を紹介します。

サンプルコード解説

import zio.{Console, ZIO, ZIOAppArgs, ZIOAppDefault}
import zio.json.*
import zio.schema.*
import zio.schema.codec.{AvroCodec, BinaryCodec, JsonCodec}

object Main extends ZIOAppDefault {
  case class Person(name: String, age: Int)

  implicit val schema: Schema[Person] = DeriveSchema.gen[Person] // (1)
  implicit val jsonCodec: JsonCodec[Person] = JsonCodec.jsonCodec(schema) // (2)
  implicit val binaryCodec: BinaryCodec[Person] = AvroCodec.schemaBasedBinaryCodec(schema) // (3)

  val person = Person("John Doe", 30)
  override def run: ZIO[ZIOAppArgs, Any, Unit] = Console.printLine(
    (
      person.toJson, // (4)
      binaryCodec.encode(person) // (5)
    )
  )
}
  1. DeriveSchema.gen[Person]で、ケースクラスPersonのスキーマを自動生成します。
  2. JsonCodec.jsonCodec(schema)で、スキーマからJSONコーデックを自動生成します。
  3. AvroCodec.schemaBasedBinaryCodec(schema)で、スキーマからAvroバイナリコーデックを自動生成します。
  4. toJsonメソッドで、PersonオブジェクトをJSON文字列に変換します。
  5. binaryCodec.encodeメソッドで、PersonオブジェクトをAvroバイナリ形式に変換します。

実行結果

このコードを実行すると、以下のような結果が得られます。

({"name":"John Doe","age":30},Chunk(16,74,111,104,110,32,68,111,101,60))

1つ目の要素はJSON形式、2つ目の要素はAvroバイナリ形式で表現されたPersonオブジェクトです。

まとめ

ZIO Schemaを使用することで、一度スキーマを定義するだけで、JSONやAvroバイナリ形式など、様々な形式へのデータ変換を簡単に行うことができます。
異なるデータ形式への変換が必要な場面で、ZIO Schemaが活用できそうですね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?