如何在swift中读取复杂的json响应?

时间:2016-06-07 07:22:54

标签: ios json xcode swift

我收到表格中的json回复 首先NSDictionary然后是NSArray(1)然后在NSArray(2)里面有一些我需要使用的数据

我无法在NSArray(2)中获取数据。请帮忙。

{
data =     {
    stores =         (
                    {
            "_id" = "************";
            address = " ";
            background = " ";
            name = " ";
            offers =                 (
                                    {
                    "_id" = 57493f4edfc5338efa2d4524;
                    description = "some description";
                    image = "https://s3-us-west-2.amazonaws.com/unishop-offers/57493f4edfc5338efa2d4524";
                    "store_id" = 57344bd40f7c7c3b1e8b97cf;
                    terms = "some terms and condition";
                },

如何从商品数据中获取图片和ID?

到目前为止,我使用了下面提到的代码:=

      if let data = dataDict["data"] as? NSDictionary{
                    if let result = data["stores"] as? NSArray{
                        for item in result{
                            print(item)
                            DataDict = [
                                "id"                     :   item["_id"] as! String,
                                "address"                :   item["address"] as! String,
                                "logo"                   :   item["logo"] as! String,
                                "name"                   :   item["name"] as! String,
                                "phone"                  :   item["phone"] as! String,
                                "offers"                 :   item["offers"] as! NSArray
                            ]
                            print(DataDict)
                            storeArray.append(DataDict)
                            tableView.reloadData()
                        }
                    }
                }

1 个答案:

答案 0 :(得分:0)

这将打印内部数组的所有键/值对

 if let data = dataDict["data"] as? [String:AnyObject],
    stores = data["stores"] as? [[String:AnyObject]] {
    for store in stores {
      if let offers = store["offers"] as?  [[String:String]] {
        for offer in offers {
          print(offer["_id"]!)
          print(offer["description"]!)
          print(offer["image"]!)
          print(offer["store_id"]!)
          print(offer["terms"]!)
        }
      }
    }
  }