提问者:小点点

Kotlin改造将JSON对象转换为Kotlin对象


我有来自一个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"}]}

使用reverfit,我尝试使用下面的代码将它转换为一个对象。为了测试,它目前被提供了一个静态变量,如邮政编码,这是已知的工作。

服务类。

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。我甚至在这两个函数中都放入了print语句,但终端中都没有显示这两个函数,以确认这两个函数都没有运行。当它发生时,终端中没有错误。


共1个答案

匿名用户

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