0
0

【Android】Retrofit2 で Kotlin Serialization を用いて変換を行う

Last updated at Posted at 2024-08-16

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()
}

/以上

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