[TIL] ๐ŸŒผ24/04/11๐ŸŒผ#Moshi & Retrofit2

0

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
79/104
post-thumbnail
post-custom-banner

[TIL] ๐ŸŒผ24/04/11๐ŸŒผ

Moshi & Retrofit2

  • ์˜ค๋Š˜์€ API ํ™œ์šฉ ๋กœ์ง์—์„œ Gson -> Moshi ์ปจ๋ฒ„ํŒ…์„ ํ•ด๋ณด์•˜๋‹ค.

๐Ÿ“Œ์ฐธ๊ณ ์ž๋ฃŒ

// Moshi adapter for List<String>
val type = Types.newParameterizedType(List::class.java, String::class.java)
val adapter = moshi.adapter<List<String>>(type)

๋ฆฌํŒฉํ† ๋ง ์ „

  • TourNetworkClient.kt
private val tourRetrofit = Retrofit.Builder()
    .baseUrl(TOUR_BASE_URL)
    .addConverterFactory(
        GsonConverterFactory.create(
            GsonBuilder()
                .setLenient()
                .create()
        )
    )
    .client(createOkHttpClient())
    .build()

๋ฆฌํŒฉํ† ๋ง ํ›„

  • build.gradle(app)์— dependency ์ถ”๊ฐ€
implementation("com.squareup.retrofit2:converter-moshi:2.9.0")
  • data class์— @SerializedName("") ์• ๋…ธํ…Œ์ด์…˜ @Json(name="")์œผ๋กœ ๋ณ€๊ฒฝ
  • TourNetworkClient.kt
private val moshi = Moshi.Builder()
     .add(KotlinJsonAdapterFactory())
     .build()

 private val tourRetrofit = Retrofit.Builder()
    .baseUrl(TOUR_BASE_URL)
    .addConverterFactory(
        MoshiConverterFactory.create(moshi).asLenient()
    )
    .client(createOkHttpClient())
    .build()
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€