ANDROID/Android 개발 이슈 & 해결

[Android] Moshi를 이용한 Retrofit2 통신

주 녕 2021. 11. 20. 08:59
728x90

최근 프로젝트를 하면서 서버와 통신하는 작업을 하게 되었습니다.

그래서 기존에 사용하던 Retrofit2와 GSON으로 작업을 진행하려고 했다가, 새롭게 사용할 라이브러리가 있을까하고 찾아보게 되었습니다. 그러다가 Android Codelabs의 'Get data from the Internet'을 보게 되었고, GSON이 아닌 Moshi라는 라이브러리를 사용하고 있다는 것을 발견했습니다!

(저는 종종 새로운 정보를 Codelabs를 통해 얻기도 합니다..!)

 

 

Moshi 라이브러리

Json과 Object를 직렬화/역직렬화를 쉽고 안전하게 할 수록 도와주는 라이브러리

 

GitHub - square/moshi: A modern JSON library for Kotlin and Java.

A modern JSON library for Kotlin and Java. Contribute to square/moshi development by creating an account on GitHub.

github.com

 

 

 

build.gradle

dependencies {
    ...
    // Retrofit
    implementation "com.squareup.retrofit2:retrofit:2.9.0"
    // Retrofit with Moshi Converter
    implementation 'com.squareup.moshi:moshi-kotlin:1.9.3'
    implementation "com.squareup.retrofit2:converter-scalars:2.9.0"
    implementation 'com.squareup.retrofit2:converter-moshi:2.9.0'
}

 

Entity - data class로 선언

data class DayStudys (
    @Json(name="year") var year: String,
    @Json(name="month") var month: String,
    @Json(name="day") var day: String, 
    @Json(name="time") var time: Int,
    @field:Json(name="studys") var studys: List<Study>, 
    @field:Json(name="focusXs") var focusXs: List<Focus> )
  • @Json(name="Json key") → 
  • @field:Json(name="Json key")  → Json key-value : JsonArray

 

Endpoint - ServerApiService.kt

private const val BASE_URL = "https://.../"
private val moshi = Moshi.Builder()
    .add(KotlinJsonAdapterFactory())
    .build()

private val retrofit = Retrofit.Builder()
    .addConverterFactory(MoshiConverterFactory.create(moshi))
    .baseUrl(BASE_URL)
    .build()

object ServerApi {
    val retrofitService : ServerApiService by lazy {
        retrofit.create(ServerApiService::class.java)
    }
}
interface ServerApiService {

    @Headers("content-type: application/json")
    @POST("stopTimer/{id}")
    suspend fun postStudyData(@Path("id") uid: String,
                              @Body studyData: StopStudys)
                              
}

 

ViewModel을 이용하여 구현하였기 때문에 아래 클래스는 ViewModel을 상속받고 있습니다!

그렇지 않은 분들은 일반 클래스에 구현하셔도 됩니다!

class ServerViewModel : ViewModel() {

    fun postStudyData(uid: String, studyData: StopStudys) {
        viewModelScope.launch {
            ServerApi.retrofitService.postStudyData(uid, studyData)
        }
    }

}
728x90