我正在嘗試新的iOS語言,但我遇到了問題。我將分析如下所示的JSON:用Swift解析Json
{
"coord":{
"lon":-0.13,
"lat":51.51
},
"sys":{
"message":0.1947,
"country":"GB",
"sunrise":1404964557,
"sunset":1405023356
},
"weather":[
{
"id":501,
"main":"Rain",
"description":"moderate rain",
"icon":"10d"
}
],
"base":"cmc stations",
"main":{
"temp":291.87,
"pressure":1018,
"humidity":87,
"temp_min":287.15,
"temp_max":295.45
},
"wind":{
"speed":3.1,
"deg":350,
"var_beg":320,
"var_end":30
},
"rain":{
"3h":0.5
},
"clouds":{
"all":75
},
"dt":1404999902,
"id":2643743,
"name":"London",
"cod":200
}
我從天氣預報服務得到了JSON,到現在爲止我做了如下方法:
func getWeatherFinished(json:NSDictionary) {
if (json != nil) {
var weather: NSArray = json.objectForKey("weather") as NSArray
var weatherDict: NSDictionary = weather.objectAtIndex(0) as NSDictionary
var weatherConditions: NSString = weatherDict.objectForKey("description") as NSString
var mainDict: NSDictionary = json.objectForKey("main") as NSDictionary
var temp: NSString = mainDict.objectForKey("temp") as NSString
var humidity: NSString = mainDict.objectForKey("humidity") as NSString
var minTemp: NSString = mainDict.objectForKey("temp_min") as NSString
var maxTemp: NSString = mainDict.objectForKey("temp_max") as NSString
var windDict: NSDictionary = json.objectForKey("wind") as NSDictionary
var speed: NSString = windDict.objectForKey("speed") as NSString
var deg: NSString = windDict.objectForKey("deg") as NSString
}
}
但是當我運行該應用程序會崩潰和我不知道爲什麼。我的代碼有什麼問題?它爲什麼會崩潰?
錯誤截圖:
當我得到的JSON我寫了這個代碼:
func connectionDidFinishLoading(connection: NSURLConnection!) {
var json: AnyObject! = NSJSONSerialization.JSONObjectWithData(receiveData, options: NSJSONReadingOptions(1), error: nil)
if let jsonDict = json as? NSDictionary {
getWeatherFinished(json as NSDictionary)
}
}
你有崩潰任何錯誤的詳細信息?此外,當類型可以由作業推斷時,您不需要將其作爲聲明的一部分包含在內。 – Joe
我把錯誤的截圖,沒有其他的信息 – lucgian841
你說'作爲NSDictionary'不允許由於錯誤JSONObjectWithData是'nil'的可能性。使用'as? NSDictionary'來獲得一個可選的'NSDictionary'('NSDictionary?')。 – Jesper