Home > other >  Access data from API request body in Kotlin
Access data from API request body in Kotlin

Time:10-04

I have just started learning Kotlin and I have a problem. I want to make an API request to get weather data from openweathermap.org, but I don't know how to access all of the values inside the response body.
Example of API response:

API response

Here is the code I have so far:

        override fun onResponse(call: Call, response: Response) {
            val body = JSONObject(response.body?.string())
            findViewById<TextView>(R.id.weatherDescription).text = body.get("weather")
        }

But I would like to get the weather Description for example, but I cant do this:

body.get("weather")[0].get("description")

So my question is, how I can access all these values.
Thanks for help in advance!

CodePudding user response:

With the implementation Klaxon, you can convert the API response to a class and then access the children.

Example (weather API):

override fun onResponse(call: Call, response: Response) {
    val body = Klaxon().parse<API_result>(response.body!!.string())
    findViewById<TextView>(R.id.windSpeed).text = "%.2f".format(body?.wind?.speed?.times(3.6)).toString()   " km/h"
    findViewById<TextView>(R.id.temperature).text = body?.main?.temp.toString()   " C"
    findViewById<TextView>(R.id.airPressure).text = body?.main?.pressure.toString()   " hPa"
}

You need to create classes with the same names as in the API result (see image in question). I choose the speed for example, which is located in "wind". So I create a data class with that a double inside. Klaxon will automatically create such a class.

Classes:

data class API_result(
    val main: main?,
    val wind: wind?
)

data class main(
    val temp: Double?,
    val pressure: Int?
)

data class wind(
    val speed: Double?
)

Then I can access these data classes created by Klaxon like

body?.wind?.speed

You will need question marks, since it is a nullable type.

CodePudding user response:

try this one:

   val desc= (body.getJSONObject("weather").getJSONObject("0")["description"] as String)

  • Related