Retorofit + JSON には「Kotlin Serialization Converter」がよい。

Retrofit は非常に有名なSquare製のJavaで書かれたAndroid 向け HTTP クライアントです。

👉 square/retrofit: Type-safe HTTP client for Android and Java by Square, Inc. 

その内部には Kotlin Serialization はサポートされていませんが、オブジェクトのシリアル化のためのコンバータファクトリを追加することができます。独自のコンバータファクトリを作成することもできますし、Jake Wharton が書いたものを使うこともできます。

👉 JakeWharton/retrofit2-kotlinx-serialization-converter: A Retrofit 2 Converter.Factory for Kotlin serialization. 

Retrofit2 Converter.Factory を利用するには、ライブラリ dependencies に追加したあと、Retorofit インスタンス生成時に、Extension Function である asConvertFactory を使ってそれを追加します。


val contentType = "application/json".toMediaType()

val retrofit = Retrofit.Builder()
 .baseUrl("https://www.example.com")
 .addConverterFactory(Json.asConverterFactory(contentType))
 .build()

簡単ですね!

ちなみに、.toMediaType() とは、


okhttp3.MediaType.Companion.toMediaType

です。

👉 「Kotlinx Json」の登場でサードパーティJSONライブラリは不要となる。