LoginSignup
1
4

More than 5 years have passed since last update.

Kotlin: Gson から Moshiに移行する

Last updated at Posted at 2017-10-28

Kotlin: Gson から Moshiに移行する

Gradleの設定

app/build.gradle

// network
def retrofitVersion = '2.3.0'
implementation "com.squareup.retrofit2:retrofit:$retrofitVersion"
implementation "com.squareup.retrofit2:adapter-rxjava2:$retrofitVersion"

// コメントアウト
//implementation "com.squareup.retrofit2:converter-gson:$retrofitVersion"

// 追加
implementation "com.squareup.retrofit2:converter-moshi:$retrofitVersion"

// 追加
def moshi_version = '1.5.0'
implementation "com.squareup.moshi:moshi:$moshi_version"
implementation "com.squareup.moshi:moshi-kotlin:$moshi_version"

モジュールの設定

ClientModule

@Module
class ClientModule {

// コメントアウト
//@Provides
//@Singleton
//fun provideGson(): Gson = GsonBuilder()
//    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
//    .create()

  @Provides
  @Singleton
  fun provideMoshi() = Moshi.Builder()
      .add(KotlinJsonAdapterFactory())
      .build()

// コメントアウト
//@Provides
//@Singleton
//fun provideRetrofit(gson: Gson): Retrofit = Retrofit.Builder()
//    .baseUrl("http://hoge.com")
//    .addConverterFactory(GsonConverterFactory.create(gson))
//    .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
//    .build()

  // 追加
  @Provides
  @Singleton
  fun provideRetrofit(moshi: Moshi): Retrofit = Retrofit.Builder()
      .baseUrl("http://hoge.com")
      .addConverterFactory(MoshiConverterFactory.create(moshi))
      .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
      .build()

  @Provides
  @Singleton
  fun provideArticleClient(retrofit: Retrofit): DiaryApi = retrofit.create(DiaryApi::class.java)
}

これでOK:beer:

ついでにJsonをパースする時にスネークケースをキャメルに変換時の方法

Diaries
data class Diaries(
    // コメントアウト
    // @SerializedName("next_offset")
    @Json(name = "next_offset")
    val nextOffset: Int,
    val items: List<Diary>
)
1
4
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
1
4