Retrofit2 で Kotlin Serialization を用いて変換を行う方法として、
Codelab では retrofit2-kotlinx-serialization-converter を使う方法が紹介されている。
手順
Kotlin Serialization をモジュールに導入する。
モジュールの build.gradle.kts の plugins
ブロックに次を追加する。
build.gradle.kts
id("org.jetbrains.kotlin.plugin.serialization") version "1.9.10"
モジュールの build.gradle.kts の dependencies
ブロックに次を追加する。
build.gradle.kts
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0")
JSON に対応するクラスを実装する
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class MarsPhoto(
val id: String,
@SerialName(value = "img_src")
val imgSrc: String
)
Retrofit2 をモジュールに導入する
モジュールの build.gradle.kts の dependencies
ブロックに次を追加する。
build.gradle.kts
implementation("com.squareup.retrofit2:retrofit:2.9.0")
Retrofit
オブジェクトをビルドする
Json.asConverterFactory("application/json".toMediaType())
でコンバーターファクトリーを生成し、
Retrofit.Builder
に追加してから
ビルドする。
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
import retrofit2.Retrofit
private val retrofit = Retrofit.Builder()
.addConverterFactory(Json.asConverterFactory("application/json".toMediaType()))
.baseUrl(BASE_URL)
.build()
private const val BASE_URL =
"https://android-kotlin-fun-mars-server.appspot.com"
使う
import retrofit2.http.GET
interface MarsApiService {
@GET("photos")
suspend fun getPhotos(): List<MarsPhoto>
}
val retrofitService: MarsApiService by lazy {
retrofit.create(MarsApiService::class.java)
}
suspend fun getPhotos(): List<MarsPhoto> {
return retrofitService.getPhotos()
}
/以上