I am using this API as a test for obtaining JSON API data. I know how to obtain the data of one of the values "grnd_level" in "list".
Here is the code I used to obtain the "grnd_level" value:
val weatherArray = forecastJson.getJSONArray("list")
for (i in 0 until weatherArray.length())
{
val grndlevel: Int
val dayForecast = weatherArray.getJSONObject(i)
val temperatureObject = dayForecast.getJSONObject("main")
grndlevel = temperatureObject.getInt("grnd_level")
But I am not sure on how to obtain the value of "name" in "city"
Very new to this so any basic help would be appreciated.
Here is an image of the API JSON:
API Image
2
Answers
The root object is
forecastJson
, you are gettinglist
array from it. Thecity
object is on the same level aslist
array, so you can getcity
object fromforecastJson
as well:And then
name
:Forget using getJSONArray and getJSONObject.
I think it’s better to use Kotlin Serialization:
You can learn about it here.
When you use this strategy, you improve readability of your code, and you have better access to properties.