Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
Kotlin serializationの使い方を詳しく調べてみた
Search
Wataru Mizukami
January 21, 2019
Programming
1.7k
2
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Kotlin serializationの使い方を詳しく調べてみた
Wataru Mizukami
January 21, 2019
More Decks by Wataru Mizukami
See All by Wataru Mizukami
GitHub Actions活用術
tarumzu
1
830
CIサービス「Bitrise」を使って 最小限の労力でDanger + ktlintをGithubと連携させる
tarumzu
1
1.1k
JavaScriptでWebViewをハックする
tarumzu
2
1.5k
Realm Cloudを使ったオフラインファーストなアプリ開発
tarumzu
2
1.1k
ViewFlipperで手軽にリッチアニメーション
tarumzu
0
620
Other Decks in Programming
See All in Programming
速習iPhone Duo対応
yuukiw00w
2
930
Unity6 URPによる海底をテーマにしたVJシステムの解説 | Unity Shader 完全に理解した 勉強会
gam0022
0
300
Workers Cache を知る
syumai
0
320
Are APIs Still Relevant in the AI Era?
soyuka
0
400
モデルのリファクタリングが難しいと思ったら、そもそも複雑だったのはビジネス仕様だった ? / is-the-business-domain-the-real-complexity
hatsu38
0
440
Vue Fes Japan 2026 タイムテーブル徹底解説
448jp
1
590
市販E-Readerを乗っ取れ 〜Embedded Swiftで電子ペーパーガジェットを制御する〜
trickart
0
230
Augmenting AI with the Power of Jakarta EE
ivargrimstad
0
390
Turning Architecture into Unit Tests in the AI Era (NSSpain XIV)
steliosf
PRO
1
120
mrbgem 三角測量 開発
ogom
0
180
手動確認はもう限界 〜XCUITestでCustom URL Schemeの遷移を起動種別ごとに自動テストする〜 / Testing Custom URL Schemes with XCUITest
otouto
0
370
JAWS-UG 東京支部が始める、JAWS-UG支部コラボ / JAWS-UG lunchtime LT Collaboration
y0hgi
0
170
Featured
See All Featured
Leo the Paperboy
mayatellez
10
2.3k
Keith and Marios Guide to Fast Websites
keithpitt
413
23k
The agentic SEO stack - context over prompts
schlessera
0
950
A Tale of Four Properties
chriscoyier
163
24k
How to Align SEO within the Product Triangle To Get Buy-In & Support - #RIMC
aleyda
2
1.8k
Rebuilding a faster, lazier Slack
samanthasiow
85
9.7k
How GitHub (no longer) Works
holman
316
150k
Writing Fast Ruby
sferik
630
63k
Design and Strategy: How to Deal with People Who Don’t "Get" Design
morganepeng
133
20k
Darren the Foodie - Storyboard
khoart
PRO
4
4k
For a Future-Friendly Web
brad_frost
183
10k
Ecommerce SEO: The Keys for Success Now & Beyond - #SERPConf2024
aleyda
1
2.2k
Transcript
Kotlin serializationの使い方を詳しく 調べてみた Wataru Mizukami(水上 亘)
自己紹介 Wataru Mizukami/水上 亘 Twitter/Github/Qiita: @tarumzu (たる) Organization/所属: sikmi, inc.
Kotlin serializationとは - シリアライザ・デシリアライザである(コード自動生成用のコンパイラプラグインとシリ アライズ用のランタイムライブラリの構成) - JSON, CBOR, Protobufの3つのフォーマットをサポートし、 さらに有志が作成したアドオンを使えばHOCON,
YAMLも使える https://github.com/Kotlin/kotlinx.serialization/blob/master/formats/README.md - Kotlin/JVM, Kotlin/JS, Kotlin/Nativeプラットフォームをサポート - リフレクションを使用しない
Kotlin serializationとは - シリアライザ・デシリアライザである(コード自動生成用のコンパイラプラグインとシリ アライズ用のランタイムライブラリの構成) - JSON, CBOR, Protobufの3つのフォーマットをサポートし、 さらに有志が作成したアドオン使えばHOCON,
YAMLも使える https://github.com/Kotlin/kotlinx.serialization/blob/master/formats/README.md - Kotlin/JVM, Kotlin/JS, Kotlin/Nativeプラットフォームをサポート - リフレクションを使用しない ー> リフレクション使用しない分速い!
build.gradle Androidでの設定方法について記述する。その他のプラットフォーム用の設定は公式参照のこと buildscript { ext.kotlin_version = '1.3.11' repositories { jcenter()
} dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version" } }
app/build.gradle apply plugin: 'kotlin' apply plugin: 'kotlinx-serialization' // 略 repositories
{ jcenter() // artifacts are published to this repository maven { url "https://kotlin.bintray.com/kotlinx" } } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.9.1" }
使い方 import kotlinx.serialization.* import kotlinx.serialization.json.JSON @Serializable data class Data(val a:
Int, @Optional val b: String = "42") fun main(args: Array<String>) { // Serializableアノテーションを付けた場合、オブジェクトを渡すだけ val jsonData = JSON.stringify(Data(42)) // コレクション等も拡張関数 serializerを使うことで利用可能 val jsonList = JSON.stringify(Data.serializer().list, listOf(Data(42))) println(jsonData) // {"a": 42, "b": "42"} println(jsonList) // [{"a": 42, "b": "42"}] // 文字列をパースするときも簡単! val obj = JSON.parse<Data>("""{"a":42}""") println(obj) // Data(a=42, b="42") } 引用元: https://github.com/Kotlin/kotlinx.serialization#quick-example
使い方2 @Serializable class Data(val a: Int) { private val b:
String = "42" override fun equals(other: Any?) = /*...*/ } // unquotedはフォーマットからダブルクォーテーションを外す assertEquals("{a:1, b:42}", JSON.unquoted.stringify(Data(1))) assertEquals(Data(1), JSON.unquoted.parse<Data>("{a:1, b:42}")) 引用元: https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/examples.md#supported-properties
アノテーションについて - Serializable : シリアライズしたいカスタムクラスに付けることでシリアライゼーションできる - Optional : 必須ではないパラメータの場合はオプショナルをつけないとエラーになる -
SerialName : JSONキー名が異なる場合に付ける - - Transient : JSONで扱わないプロパティを定義したい場合に使用する。 JSONにこのプロパティが存在していた場合エラーになる - SerialInfo : アノテーションクラスを定義するためのアノテーション。 プロパティにタグなどの情報をもたせることが出来て、 エンコーダー内でタグをもとに条件分岐などに利用できる。 Protobufなどで利用する
アノテーションの使い方 // シリアライズしたいクラスに付与 @Serializable data class Data( val a: Int,
// 必須パラメーターではない場合に付ける @Optional val b: String = “42”, // jsonキー名がcでプロパティ名とことなる場合 @SerialName("c") val d: String ) - SerialInfoの例は下記参照 https://github.com/Kotlin/kotlinx.serialization/blob/bb6e21e2c05cf6fa7d9a1b7f0c401d0afe726eda/runtime/com mon/src/test/kotlin/kotlinx/serialization/protobuf/SampleClasses.kt
カスタムシリアライザ シリアライザを自作することも可能。このサンプルは日付を扱う例 @Serializer(forClass = Date::class) object DateSerializer: KSerializer<Date> { private
val df: DateFormat = SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS") override val descriptor: SerialDescriptor = StringDescriptor.withName("WithCustomDefault") override fun serialize(output: Encoder, obj: Date) { output.encode(df.format(obj)) } override fun deserialize(input: Decoder): Date { return df.parse(input.decode()) } } 引用元: https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/custom_serializers.md#external-serializers-for-library-classes
ご清聴、ありがとうございました!