Reputation: 1
Here is JSON file
{
"weather":[
{
"id":804,
"main":"Clouds",
"description":"overcast clouds",
"icon":"04d"
}
],
"main":{
"temp":273.15,
"pressure":1035,
"humidity":84,
"temp_min":273.15,
"temp_max":273.15
},
"name":"Wroclaw",
}
Here is code.
var cityName: String!
var degree: Int!
var someWeather: String!
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
if let main = json["main"] as? [String : AnyObject] {
if let temp = main["temp"] as? Int {
self.degree = temp
}
}
if let city = json["name"] as? String {
self.cityName = city
}
}
if let weather = json["weather"] as? [String : AnyObject] {
if let someWeather = weather["main"] as? String {
self.weatherDescription = someWeather
}
}
labelWeather.text = self.weatherDescription
How to save to variable weatherDescription the value of "main" or "description" from weather in json? I try like in this code, but it doesn't show me anything . Degrees and city name works correct and shows, but weather doesn't work.
Updated code //////////////////////////////////////
var let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
if let main = json["main"] as? [String : AnyObject] {
if let temp = main["temp"] as? Int {
self.degree = temp
}
if let pressuer = main["pressure"] as? Int {
self.cisnienie = pressuer
}
}
if let weather = json["weather"] as? [[String : Any]] {
for data in weather {
if let main = data["main"] as? String {
print(main)
}
}
}
if let nazwa = json["name"] as? String {
self.nazwaMiasta = nazwa
}
Here is all JSON file:
{
"coord":{
"lon":-0.13,
"lat":51.51
},
"weather":[
{
"id":800,
"main":"Clear",
"description":"clear sky",
"icon":"01d"
}
],
"base":"stations",
"main":{
"temp":279.07,
"pressure":1032,
"humidity":52,
"temp_min":278.15,
"temp_max":280.15
},
"visibility":10000,
"wind":{
"speed":7.2,
"deg":80
},
"clouds":{
"all":0
},
"dt":1484923800,
"sys":{
"type":1,
"id":5091,
"message":0.0087,
"country":"GB",
"sunrise":1484898825,
"sunset":1484929819
},
"id":2643743,
"name":"London",
"cod":200
}
Upvotes: 0
Views: 249
Reputation: 22374
"weather" is an array
not dictionary
..
if let weather = json["weather"] as? [[String : Any]] {
for data in weather{
if let main = data["main"] as? String{
print(main)
}
}
}
Upvotes: 1