使用okHTTP和GSON从API中提取数据

对于使用API​​(和kotlin)这个新手来说,我很难弄清楚如何从API中将数据提取到模型对象中,并且希望有人能指出我的正确方向。 下面的示例代码。

val request = Request.Builder().header("X-Mashape-Key", keyVal).url(url).build() //make request client val client = OkHttpClient() //create request client.newCall(request).enqueue(object: Callback { override fun onResponse(call: Call?, response: Response?) { //grab as string, works fine val body = response?.body()?.string() //make my builder, works fine val gson = GsonBuilder().create() // to pass type of class to kotlin :: val cardFeed = gson.fromJson(body, CardFeed::class.java) } override fun onFailure(call: Call?, e: IOException?) { println("Failed to execute request") } }) } 

所有这一切似乎在调试中按预期工作,我得到的字符串,并可以看到它,但使用以下它仍然将空转入cardFeed /卡对象。

 class CardFeed(val cards: List) class Card(val cardId: String, val name: String, val text: String, val flavor: String) 

我从API获取的正文字符串如下所示

body:“{Basic”:[{“key”:“value”等等)

我假设[是什么让我绊倒,但不知道如何纠正。

任何想法或推动正确的方向将不胜感激,并提前感谢。

根据你的类结构,你应该从API获得的JSON对象应该是

 { "cards":[ { "cardId":"", "name":"", "flavor":"" }, { "cardId":"", "name":"", "flavor":"" } ] } 

使用正确的键,因为当你使用gson.fromJson(body, CardFeed::class.java) ,它会查找分配的类(CardFeed.java)中的variables名。 如果你没有正确的键(“卡”,“cardId”,“名称”,“味道”),gson会返回null

okHttp是一个低级库。 为了使用基于JSON的API, Retrofit是一个更合适的库,因为它已经有使用像GSON或Moshi这样的库的转换器来完成所有繁重的工作。