【发布时间】: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