【问题标题】:Kotlin retrofit convert JSON object to Kotlin ObjectKotlin 改造将 JSON 对象转换为 Kotlin 对象
【发布时间】:2021-07-03 10:42:36
【问题描述】:

我有来自类似这样的 API 的数据

{"post code": "45219", "country": "United States", "country abbreviation": "US", "places": [{"place name": "Cincinnati", "longitude": "-84.5131", "state": "Ohio", "state abbreviation": "OH", "latitude": "39.127"}]}

使用 Retrofit 我尝试使用以下代码将其转换为对象。为进行测试,目前正在为它提供一个静态变量作为已知有效的邮政编码。


服务类。

class AddressService {

fun fetchCityAndState(zipCode : String) : MutableLiveData<Address>{
    var _addresses = MutableLiveData<Address>()
    val service = RetroFitClientInstance.retrofitInstace?.create(IAddressDAO::class.java)
    val call = service?.getLocation("https://api.zippopotam.us/us/$zipCode")
    call?.enqueue(object: Callback<Address> {
        override fun onFailure(call: Call<Address>, t: Throwable) {
            print("Could not retrieve service response")
        }

        override fun onResponse(call: Call<Address>, response: Response<Address>) {
            _addresses.value = response.body()
        }
    })
    return _addresses
}

地址类

data class Address(@SerializedName("post code") var postCode: String, @SerializedName("country") var country: String, @SerializedName("country abbreviation") var countryAbbreviation: String, @SerializedName("places") var placeInformation: ArrayList<Location>)

位置类

class Location (@SerializedName("place name") var name: String, @SerializedName("longitude") var longitude: String, @SerializedName("state") var state: String, @SerializedName("state abbreviation") var stateAbbreviation: String, @SerializedName("latitude") var latitude: String)

地址接口

@GET
fun getLocation(@Url zipCodeUrl:String) : Call<Address>

使用调试器时,我看到调用跳过了 onFailure 和 onResponse 函数,只是返回 _addresses 仍然为空。我什至在两个函数中都放了打印语句,但都没有出现在终端中以确认两个函数都没有运行。发生这种情况时,终端中没有错误。

编辑 1

改造客户端实例

object RetroFitClientInstance {

private var retrofit : Retrofit? = null
private var BASE_URL = "https://api.zippopotam.us"

val retrofitInstace : Retrofit?
    get() {
        if (retrofit == null) {
            retrofit = retrofit2.Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
        }
        return retrofit
    }

}

【问题讨论】:

    标签: android api kotlin retrofit


    【解决方案1】:

    您将在观察此实时数据的位置看到变化。

    onResponse 或 onFailure 不会立即调用,因为有异步调用尝试在 onResponse 块和 onFailure 块中添加断点

    还在观察此实时数据的位置添加断点

    fetchCityAndState().observe(viewLifecycleOwner,youObserver {
    
    })
    

    【讨论】:

      【解决方案2】:

      您是否正确配置了改造?分享代码或确保你传递了okhttpclient和转换器(通常是gson转换器)

      【讨论】:

      • 我相信是的,我已将文件添加到问题中。
      猜你喜欢
      • 1970-01-01
      • 2017-10-15
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      • 2019-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多