Android Kotlin改造将JSON对象转换为Kotlin对象
我有一个API的数据,看起来像这样Android Kotlin改造将JSON对象转换为Kotlin对象,android,api,kotlin,retrofit,Android,Api,Kotlin,Retrofit,我有一个API的数据,看起来像这样 {"post code": "45219", "country": "United States", "country abbreviation": "US", "places": [{"place name": "Cincinnati", "longitude"
{"post code": "45219", "country": "United States", "country abbreviation": "US", "places": [{"place name": "Cincinnati", "longitude": "-84.5131", "state": "Ohio", "state abbreviation": "OH", "latitude": "39.127"}]}
使用改型,我尝试使用下面的代码将其转换为一个对象。为了进行测试,目前正在将一个静态变量作为已知有效的邮政编码提供给它
服务舱
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
}
地址接口
@GET
fun getLocation(@Url zipCodeUrl:String) : Call<Address>
}您是否正确配置了改装?共享代码或确保您传递了okhttpclient和converter(通常是gson converter)您将在观察到此实时数据的地方看到更改 onResponse或onFailure不会立即调用,因为有异步调用尝试在onResponse块和onFailure块中添加断点 还可以在观察实时数据的位置添加断点
fetchCityAndState().observe(viewLifecycleOwner,youObserver {
})
我想是的,我已经把文件添加到问题中了。
@GET
fun getLocation(@Url zipCodeUrl:String) : Call<Address>
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
}
fetchCityAndState().observe(viewLifecycleOwner,youObserver {
})