从Swift 2.0中的JSON对象获取值

时间:2015-12-03 00:37:38

标签: json swift

我有以下JSON并通过JSONLint.com验证,我唯一的问题是我似乎无法从中获取所有值。

{
"success": true,
"message": null,
"content": [{
    "url": "6\/image_2.png",
    "date_added": "2015-12-02 22:43:05",
    "comments": ["Awesome Pic", "WOOHOOOOO THIS IS GREAT"],
    "likes": []
}, {
    "url": "6\/image_4.png",
    "date_added": "2015-12-02 22:42:59",
    "comments": [],
    "likes": []
}, {
    "url": "2\/image_1.png",
    "date_added": "2015-12-01 06:43:48",
    "comments": [],
    "likes": []
}, {
    "url": "2\/image_4.png",
    "date_added": "2015-12-01 06:43:48",
    "comments": [],
    "likes": []
}, {
    "url": "2\/image_5.png",
    "date_added": "2015-12-01 06:43:48",
    "comments": ["EhHHHH"],
    "likes": []
}]}

我尝试了一切,但它失败了。这是我到目前为止所拥有的。

if(response["success"] as! Int == 1){
     if let images = response["content"] as AnyObject?{
          // Does not work if I put NSDictionary? instead of AnyObject
          // PRINTS THE OBJECT
          print(images)
          if let url = images["url"] as String?{
              // DOES NOT WORK
              print(url)
          }
      }
  }else{
      // Print error
      let response = response["message"] as! String
      print(response)
  }

1 个答案:

答案 0 :(得分:2)

content是一个集合,而不是一个对象。因此,您应该将其转换为NSDictionary而不是NSArray,而是遍历每个项目。

 let isSuccess = response["success"] as! Bool
 if(isSuccess)
 {
    if let dataArr=response["content"] as? NSArray
    {
      for item in dataArr
      {
         if let itemDict = item as? NSDictionary
         {
            let url= itemDict["url"] as! String
            //Access other properties also here
         }
      }
    }
}