I'm trying to parse a JSON from a url but the JSON happens to be double nested, and I'm not sure how to make it work with my code Here's the JSON and its link:
{
"status":"success",
"data":{
"city":"London",
"state":"England",
"country":"United Kingdom",
"location":{
"type":"Point",
"coordinates":[
0.040725,
51.456357
]
},
"current":{
"weather":{
"ts":"2022-03-12T19:00:00.000Z",
"tp":9,
"pr":1008,
"hu":76,
"ws":5.14,
"wd":130,
"ic":"01n"
},
"pollution":{
"ts":"2022-03-12T19:00:00.000Z",
"aqius":27,
"mainus":"p2",
"aqicn":9,
"maincn":"p2"
}
}
}
}
Code:
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
response -> {
try {
JSONArray jsonArray = new JSONArray();
//Accessing "data" in the JSON
jsonArray.put(response.get("data"));
for (int i = 0; i < jsonArray.length(); i ){
JSONObject data = jsonArray.getJSONObject(i);
String cityName = data.getString("city");
String stateName = data.getString("state");
String countryName = data.getString("country");
}
//Notifying the adapter of the new changes
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}, Throwable::printStackTrace);
requestQ.add(request);
}
GOAL:
I want the function to read "current" and then "weather" and then get the value of "tp" just like how I'm getting the value of cityName, stateName etc I'm aware that this question has been answered before but I didn't find something for double nested JSONs
Thanks a lot in advance.
CodePudding user response:
You can get the nested object by
yourObject.getJSONObject("weather")
In your case, it would be:
data.getJSONObject("current").getJSONObject("weather").getInt("tp");
Also, you could use the library gson to map the json string to Java class.