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
CodePudding user response:
The root object is forecastJson, you are getting list array from it. The city object is on the same level as list array, so you can get city object from forecastJson as well:
val city = forecastJson.getJSONObject("city")
And then name:
val name = city.getString("name")
CodePudding user response:
Forget using getJSONArray and getJSONObject. I think it's better to use Kotlin Serialization:
val data = Project()
val string = Json.encodeToString(data)
// Deserializing back into objects
val obj = Json.decodeFromString<Project>(string)
You can learn about it here. When you use this strategy, you improve readability of your code, and you have better access to properties.
