本文将展示如何在Android项目中使用Moshi(代替Gson的项目)配合Retrofit实现Json解析
首先,你为什么要使用Moshi代替Gson呢?
https://www.reddit.com/r/androiddev/comments/684flw/why_use_moshi_over_gson/
如何在Kotlin中使用Retrofit和Moshi?
添加依赖(Dependencies)
1
2
3dependencies {
implementation "com.squareup.retrofit2:converter-moshi:2.4.0"
}注意:如果你仅仅在
Retrofit中使用Gson,记得移除Gson的依赖添加Moshi转换到
Retrofit中1
2
3
4val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com")
.addConverterFactory(MoshiConverterFactory.create())
.build()注意:需要在
Retrofit初始化的地方实现Moshi的转换工厂方法,用来代替.addConverterFactory(MoshiConverterFactory.create())。不要忘记移除
GsonConverterFactory更新你的网络数据
1
2data class UserEntity((name = "id") val id: String,
(name = "name") val name: String)注意:Moshi中的
@Json等效于Gson中的@SerializedName,不要忘记将@SerializedName替换为@Json。为了防止因为混淆造成数据不可用,最好使用注释(即使变量的名称与JSON Key相同)
本文只是简单介绍了Moshi,更多功能请前往Moshi主页查看