はじめに
今回はGsonが非推奨なのでMoshiを使ってのJson変換を紹介していきます
本文
コード自体は下記の通りです
Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
.adapter(HogeData::class.java)
.fromJson(Json)
adapter
の中には変換先のデータクラスを渡し、fromJson
には変換したいJson
を渡します。
ここで2点注意が必要なのですが、
1つ目が.add(KotlinJsonAdapterFactory())
Kotlin用のFactoryを追加することです
2つ目は変換先のデータクラスで下記二つのアノテーションをつけることです。
データクラス自体には@JsonClass(generateAdapter = true)
各種変数には@Json(name = "hoge")
最後に
今回はだんだんと増えてくるであろうMoshiの実装方法を紹介していきました
どなたかのお役に立てれば幸いです