I am new to Kotlin beginner and trying to create a code to fetch data from JSON.
I'd like to fetch the data from "value" inside "forecastMaxtemp".
Here is my code. I am tried as below but not successful.
...
Response.Listener { response ->
temp.text =
response.getJSONArray (name"weatherForecast").
getJSONObject(0).
getJSONObject("forecastMaxtemp").
getString(name"value")
},
JSON Data
{"generalSituation":No Alarm",
"weatherForecast":[{
"forecastDate":"20211004",
"week":"Monday",
"forecastWind":"East force 4 to 5.",
"forecastWeather":"Sunny periods.",
"forecastMaxtemp":{"value":31,"unit":"C"},
"forecastMintemp":{"value":27,"unit":"C"},
...
...
]
}
CodePudding user response:
{"value":31,"unit":"C"}
here 31
is int, so use getInt()
function.
response.getJSONArray ("weatherForecast").
getJSONObject(0).
getJSONObject("forecastMaxtemp").
getInt("value")
}
CodePudding user response:
Your JSON has an issue, I think this is the right format:
{
"generalSituation": "No Alarm",
"weatherForecast": [
{
"forecastDate": "20211004",
"week": "Monday",
"forecastWind": "East force 4 to 5.",
"forecastWeather": "Sunny periods.",
"forecastMaxtemp": {
"value": 31,
"unit": "C"
},
"forecastMintemp": {
"value": 27,
"unit": "C"
}
}
]
}
to get the value from "forecastMaxtemp",
val json = JSONObject("YOUR_JSON")
val obj = json.getJSONArray("weatherForecast").get(0) as JSONObject
val value = obj.getJSONObject("forecastMaxtemp").getInt("value")