Chris Peragine
Chris Peragine

Reputation: 178

Pulling data from an API with okHTTP & GSON

New to using API's (and kotlin for that matter) and I'm having some trouble figuring out how to pull data from an API into model objects and was hoping someone could point me in the right direction. Sample code below.

    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")
        }
    })
}

All of that seems to work as intended in debug, I get the string, and can see it but using the following it still dumps a null into the cardFeed/cards object.

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

The body string I'm getting from the API reads as follows

body: "{Basic":[{"key":"value", etc

I'm assuming the [ is what's tripping me up, but not sure how to correct it.

Any ideas or nudges in the correct direction would be greatly appreciated and thanks ahead of time.

Upvotes: 0

Views: 6340

Answers (2)

Napster
Napster

Reputation: 1383

According to your class structure, the JSON object that you should get from the API should be

{  
   "cards":[  
      {  
         "cardId":"<cardID>",
         "name":"<name>",
         "flavor":"<flavor>"
      },
      {  
         "cardId":"<cardID>",
         "name":"<name>",
         "flavor":"<flavor>"
      }
   ]
}

with the correct keys because when you use gson.fromJson(body, CardFeed::class.java), it looks for the variable names in the class assigned (CardFeed.java). If you don't have the correct keys ("cards", "cardId", "name", "flavor"), gson would return null for the values

Upvotes: 1

Xavier Rubio Jansana
Xavier Rubio Jansana

Reputation: 6583

okHttp is a low level library. In order to consume JSON based APIs, Retrofit is a much more suitable library, as it already have converters that use libraries like GSON or Moshi to do all the heavy lifting for you.

Upvotes: 1

Related Questions