【问题标题】:How to read complicated json response in swift?如何快速读取复杂的 json 响应?
【发布时间】:2016-06-07 07:22:53
【问题描述】:

我收到表单中的 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";
                },

如何从 offer 数组中获取图片和 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()
                        }
                    }
                }

【问题讨论】:

  • 您的 JSON 无效。数组应该用'['标记,而不是'('。
  • 它非常有效,我可以使用 NSDictionary 和 NSArray 从上述响应中提取数据,而且数组始终标有“()”,然后内部响应是标有“{ }"
  • @EICaptainv2.0 先生,我已经发布了我的代码作为答案
  • @RajatAttri 提供的是一个数组......所以你需要遍历它并从那里访问图像和 id
  • @Raphaël 我们在这里看到的不是 JSON,而是由 JSON 生成的 NSArray/NSDictionary 的打印结果。

标签: ios json xcode swift


【解决方案1】:

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

 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"]!)
        }
      }
    }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多