从Swift 2.0中的JSON对象获取值

时间:2022-10-10 21:16:22

I have the following JSON and it is validated via JSONLint.com, my only issue is that I can't seem to get all the values out from it.

我有以下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": []
}]}

I tried everything but it just fails. Here is what I have so far.

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

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 个解决方案

#1


2  

content is an collection, not a single object. So instead of NSDictionary, you should cast it to NSArray and iterate through each item.

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

 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
         }
      }
    }
}

#1


2  

content is an collection, not a single object. So instead of NSDictionary, you should cast it to NSArray and iterate through each item.

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

 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
         }
      }
    }
}