I am currently using Openweathermap.org to get weather forecast information. And here is the JSON objects I got from their API:
{
"city":{ },
"cod":"200",
"message":0.0029,
"cnt":40,
"list":[
{
"dt":1466532000,
"main":{
"temp":296.52,
"temp_min":294.864,
"temp_max":296.52,
"pressure":1004.95,
"sea_level":1023.45,
"grnd_level":1004.95,
"humidity":58,
"temp_kf":1.65
},
"weather":[
{
"id":803,
"main":"Clouds",
"description":"broken clouds",
"icon":"04d"
}
],
"clouds":{ },
"wind":{ },
"sys":{ },
"dt_txt":"2016-06-21 18:00:00"
},
{
"dt":1466542800,
"main":{ },
"weather":[ ],
"clouds":{ },
"wind":{ },
"sys":{ },
"dt_txt":"2016-06-21 21:00:00"
},
{
"dt":1466553600,
"main":{ },
"weather":[ ],
"clouds":{ },
"wind":{ },
"sys":{ },
"dt_txt":"2016-06-22 00:00:00"
}]
}
As you can see from this sample, under list there are many objects and what I want is just the temp and the weather main and description. I created a Struct to sort and hold all of the JSON objects but it keeps giving me errors. How do I sort it in terms of the "dt" and how would I extract the data from the JSON. Thanks.
Here is my Struct:
import Foundation
struct FutureWeather {
//future stuff
var futureDt: NSDate //
var futureMainWeather: String//
var futureDescription: String//
private var futureTemp: Double//
var futureTempCelsius: Double {
get {
return futureTemp - 273.15
}
}
var futureTempFahrenheit: Double {
get {
return (futureTemp - 273.15) * 1.8 + 32
}
}
init(futureWeatherData : [String:AnyObject]) {
//first set of data
let futureWeatherDictUno = futureWeatherData["list"]![0] as! [String: AnyObject]
print(futureWeatherDictUno)
let events = futureWeatherDictUno.sort({$0["dt"] < $1["dt"]})
futureDt = NSDate(timeIntervalSince1970: futureWeatherDictUno["dt"] as! NSTimeInterval)
let mainDictOne = futureWeatherDictUno["main"] as! [String: AnyObject]
futureTemp = mainDictOne["temp"] as! Double
let weatherDictOne = futureWeatherDictUno["weather"]![0] as! [String: AnyObject]
futureMainWeather = weatherDictOne["main"] as! String
futureDescription = weatherDictOne["description"] as! String
//the second set of data
let futureWeatherDictDos = futureWeatherData["list"]![1] as! [String: AnyObject]
futureDt = NSDate(timeIntervalSince1970: futureWeatherDictUno["dt"] as! NSTimeInterval)
let mainDictTwo = futureWeatherDictDos["main"] as! [String: AnyObject]
futureTemp = mainDictTwo["temp"] as! Double
let weatherDictTwo = futureWeatherDictDos["weather"]![0] as! [String: AnyObject]
futureMainWeather = weatherDictTwo["main"] as! String
futureDescription = weatherDictTwo["description"] as! String
}
}
Aucun commentaire:
Enregistrer un commentaire