Moshi配合Retrofit在Kotlin中的使用

本文将展示如何在Android项目中使用Moshi(代替Gson的项目)配合Retrofit实现Json解析

首先,你为什么要使用Moshi代替Gson呢?

https://www.reddit.com/r/androiddev/comments/684flw/why_use_moshi_over_gson/

如何在Kotlin中使用Retrofit和Moshi?

  1. 添加依赖(Dependencies)

    1
    2
    3
    dependencies {
    implementation "com.squareup.retrofit2:converter-moshi:2.4.0"
    }

    注意:如果你仅仅在Retrofit中使用Gson,记得移除Gson的依赖

  2. 添加Moshi转换到Retrofit

    1
    2
    3
    4
    val retrofit = Retrofit.Builder()
    .baseUrl("https://api.example.com")
    .addConverterFactory(MoshiConverterFactory.create())
    .build()

    注意:需要在Retrofit初始化的地方实现Moshi的转换工厂方法,用来代替.addConverterFactory(MoshiConverterFactory.create())

    不要忘记移除GsonConverterFactory

  3. 更新你的网络数据

    1
    2
    data class UserEntity(@field:Json(name = "id") val id: String,
    @field:Json(name = "name") val name: String)

    注意:Moshi中的@Json等效于Gson中的@SerializedName,不要忘记将@SerializedName替换为@Json

    为了防止因为混淆造成数据不可用,最好使用注释(即使变量的名称与JSON Key相同)

    本文只是简单介绍了Moshi,更多功能请前往Moshi主页查看