0

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"},
...
...
]
}
1
  • Thank you for your suggestion How can I modify it If I would like to get both values in one JSONObject ("value" and "unit") Commented Oct 5, 2021 at 2:56

2 Answers 2

1

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")
Sign up to request clarification or add additional context in comments.

Comments

0

{"value":31,"unit":"C"} here 31 is int, so use getInt() function.

response.getJSONArray ("weatherForecast").
getJSONObject(0).
getJSONObject("forecastMaxtemp").
getInt("value")
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.