提取JSON数据 -

时间:2017-03-05 17:49:49

标签: arrays json swift nsdictionary fbsdk

我从FBSDKGraphRequest中提取了以下JSON数据结构。

data =     (
            {
        id = "<USER_ID_GOES_HERE>";
        name = "Tom Jones";
        picture =             {
            data =                 {
                "is_silhouette" = 0;
                url = "<USER_IMAGE_URL_GOES_HERE>";
            };
        };
    },
            {
        id = "<USER_ID_GOES_HERE>";
        name = "Tom Jones";
        picture =             {
            data =                 {
                "is_silhouette" = 0;
                url = "<USER_IMAGE_URL_GOES_HERE>";
            };
        };
    },
            {
        id = "<USER_ID_GOES_HERE>";
        name = "Tom Jones";
        picture =             {
            data =                 {
                "is_silhouette" = 0;
                url = "<USER_IMAGE_URL_GOES_HERE>";
            };
        };
    },

我想提取数据并将其放入数组中。我对第一个“数据”键有困难。

继承我的FBSDKGR:

let params = ["fields": "name, picture.type(large)"]
    let request = FBSDKGraphRequest(graphPath: "me/taggable_friends", parameters: params)
    request!.start { (connection, result, error) -> Void in

        if error != nil {
            print("There is some error getting friends", error!)
        }
        else if result != nil {
            print("Here is the result", result!)

2 个答案:

答案 0 :(得分:1)

With an extra dependency, if you don't mind.

import SwiftyJSON

let json = JSON(result) // after you get result from FBSDKGR
let data = json["data"].array
for (index, _) in data.enumerated() {
     if let id = json["data", index, "id"].int {
          // add to your array
          if let name = json["data", index, "name"].string {
              // continue nesting...
         }
     } 
}

答案 1 :(得分:0)

由于你的JSOND dta是字典数组,我们可以通过以下方式转换结果。首先,我们将采用两个数组,一个用于名称列表,另一个用于图片详细信息。这里图片细节数组是字典数组。我们去找代码

var namesArray = [String]()
var ImageDetailsArrayDict= [[String :AnyObject]]()

let params = ["fields": "name, picture.type(large)"]
    let request = FBSDKGraphRequest(graphPath: "me/taggable_friends", parameters: params)
    request!.start { (connection, result, error) -> Void in

        if error != nil {
            print("There is some error getting friends", error!)
        }
        else if result != nil {
            print("Here is the result", result!)
         if let response = result["data"] as? [[String :AnyObject]] {

               for i in 0..<response.count {
                  namesArray.append(response[i]["name"] as! String)                
                  ImageDetailsArrayDict.append(response[i]["picture"])

                 }
              }
          }
      }

现在,我们有两个数组。所以我们可以在tableView中轻松填充它。    祝你好运。