Reputation: 47
All I am getting resources are getting JSONObject
from JSONArray
. But in this case, I want to get the temperature which is "temp". I don't think it is part of an array. How can I get that?
{
"coord":{
"lon":85.17,
"lat":26.67
},
"weather":[
{
"id":500,
"main":"Rain",
"description":"light rain",
"icon":"10d"
}
],
"base":"stations",
"main":{
"temp":31.09,
"pressure":1004.15,
"humidity":83,
"temp_min":31.09,
"temp_max":31.09,
"sea_level":1010.39,
"grnd_level":1004.15
},
"wind":{
"speed":3.66,
"deg":107.5
},
"rain":{
"3h":0.202
},
"clouds":{
"all":64
},
"dt":1534148929,
"sys":{
"message":0.0048,
"country":"IN",
"sunrise":1534117810,
"sunset":1534165068
},
"id":1273043,
"name":"Dhaka",
"cod":200
}
I have tried- (I am new with JSON)
JSONObject jsonObject = new JSONObject(s);
JSONObject main = jsonObject.getJSONObject("main");
JSONObject temp = main.getJSONObject("temp");
Upvotes: 1
Views: 1067
Reputation: 3265
temp is not a JSonObject. you can get the temperature as String or double. So change the last line of your code with:
String temp = main.getString("temp");
or
double temp = main.getDouble("temp");
Upvotes: 0
Reputation: 52013
Get the value from main
object using "temp" as key
double temp = main.getDouble("temp");
Upvotes: 0
Reputation: 72344
Assuming you're using Android (tagging appropriately helps here, as it depends on the JSON library you're using):
Since you've got JSONObject main = jsonObject.getJSONObject("main");
, you should then just be able to do double temp = main.getDouble("temp");
to get the temperature off that main
object.
If you have a look at the docs for JSONObject you can see a variety of methods for getting JSON "primitive" fields, such as int
, String
, etc. - and you need to use those to retrieve said primitive fields, rather than calling getJSONObject()
.
Upvotes: 2