之前使用的一直是Retrofit+Gson,后来看到说Moshi更适合kotlin,尝试使用
核心区别就是Retrofit配置的convertAdapter
moshi的引入
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation "com.squareup.retrofit2:converter-moshi:2.9.0"
implementation "com.squareup.moshi:moshi-kotlin:1.15.0"
implementation "com.squareup.moshi:moshi-adapters:1.15.0"
在RetrofitClient中的配置
val moshi = Moshi.Builder().addLast(KotlinJsonAdapterFactory()).build()
Retrofit.Builder().baseUrl(url)
.client(okHttpClient)
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build()
之后的使用和GSON基本一致
一个小问题记录
我的项目开启了压缩与混淆,然后一直报JSON转换错误
最后发现是混淆文件写错了,没有keep自定义类型,被混淆了,然后一直报错
所以,一定要记得:
-keep class 数据包名.** { *; }