用Swift解析Json

时间:2014-07-10 13:53:07

标签: ios json swift

我尝试使用新的iOS语言,但我遇到了问题。我将解析如下的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
    }
}

但是,当我运行该应用程序时,它崩溃了,我不知道为什么。我的代码有什么问题?为什么会崩溃?

ERROR SCREENSHOT: enter image description here

当我收到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)
        }

}

1 个答案:

答案 0 :(得分:2)

尝试检查以确保您的JSON是非零的并且可以是字典:

func connectionDidFinishLoading(connection: NSURLConnection!) {
    var json: AnyObject! = NSJSONSerialization.JSONObjectWithData(receiveData, options: NSJSONReadingOptions(1), error: nil)
    if let jsonDict = json as? NSDictionary{
        getWeatherFinished(json)
    }

}

此行崩溃,因为具有键'temp'的对象不是NSString。

var temp: NSString = mainDict.objectForKey("temp") as NSString

从你的json看起来它是一个数字,所以你可以试试这个:

var tempNum: NSNumber = mainDict.objectForKey("temp") as NSNumber
var temp: NSString = tempNum.stringValue()