Swift:解析JDS,NSDictionaries的NSDictionary

时间:2015-02-26 08:46:44

标签: ios json swift nsdictionary

我正在尝试使用一些标记和子标记解析JSON文件。我是通过创建NSDictionary来做到这一点的。由此我从某个标签创建NSDictionary。此NSDictionary包含我要解析的属性。所以我试图遍历NSDictionary,但它无效。我尝试了很多变种,但它不断给我编译错误。

var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(JSONData, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

var devices:NSDictionary = jsonResult.objectForKey("devices") as NSDictionary

for device:NSDictionary in devices{

    device.objectForKey("id")
    //etc
    //etc
}

我收到以下错误:

'(key: AnyObject, value: AnyObject)' is not convertible to 'NSDictionary'
每个循环行上的

。我之后也试过把它投射到NSDictionary,但后来我得到了同样的错误。

为了澄清,这是我的json文件的示例:

{  
   "global":{  
      //etc
   },
   "user":{  
    //etc
   },
   "devices":[  
      {  
         "id":16108,
         //etc
      },
      {
          “id”:12310,
          //etc
      },
        //etc
},

等显然意味着更多的数据,这只是一个基本的大纲。我正在尝试阅读设备的属性

2 个答案:

答案 0 :(得分:3)

此处的问题是objectForKey("devices")返回NSArray而不是NSDictionary

答案 1 :(得分:-1)

适合我:

        var error: NSError?
        var jsonResult = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary

        var devices = jsonResult.objectForKey("devices") as NSArray?
        if devices != nil {
            for device in devices! {
                var deviceId = device.objectForKey("id") as NSNumber
                println("deviceId: \(deviceId)")
            }
        }