循环播放来自Alamofire的{JSON响应

时间:2015-12-22 09:21:09

标签: ios json loops swift2

我正在使用xcode 7.2和swift 2.1.1。使用Alamofire进行服务器通信。我有一个显示动态数据的tableview.Data包括username,useremail,profilePicture等。我试图从stackoverflow实现this代码。但我收到一条警告信息说来自' JSON'到不相关的类型' [字典]'总是失败我的json回复是

{
  "JsonRequestBehavior" : 1,
  "MaxJsonLength" : null,
  "ContentType" : null,
  "Data" : {
    "_id" : "5658444778a7531f4c79c23d",
    "Photo" : "",
    "AllowSharing" : "YES",
    "MemberCount" : 5,
    "Users" : [
      {
        "_id" : "5658443478a7531f4c79c23c",
        "Photo" : "",
        "MembershipDate" : "0001-01-01T00:00:00",
        "MiddleName" : null,
        "FirstName" : "Gohan",
        "LastName" : null,
        "Email" : "gohan@gmail.com"
      },
      {
        "_id" : "566ea5f1dfead62350cf0fad",
        "Photo" : "",
        "MembershipDate" : "0001-01-01T00:00:00",
        "MiddleName" : null,
        "FirstName" : null,
        "LastName" : null,
        "Email" : "sachin@gmail.com"
      }
    ],
    "MembershipDate" : "2015-12-14T12:03:12.819Z",
    "CreatedBy" : "5658443478a7531f4c79c23c"
  },
  "ContentEncoding" : null,
  "RecursionLimit" : null
}

如何在JSON响应中循环用户

编辑根据JohnyKutty的回答我在我的项目中尝试了相同的代码。相同的代码是

 Alamofire.request(.GET,App.AppHomeURL() + "Load_Group", parameters: ["groupid":"\(groupId)"]).responseJSON
            {
                response in
                 print("\(response.data)")
                switch response.result
                {

                case .Success(let _data):
                    let jsonData = JSON(_data)
                    print("Admin Response : \(jsonData)")

                do
                   {
                    let json = try NSJSONSerialization.JSONObjectWithData(_data as! NSData, options: .AllowFragments) as! NSDictionary
                        if let DataObject = json["Data"] as? NSDictionary
                        {
                            if let users = DataObject["Users"] as? [NSDictionary]
                            {
                                for user in users
                                {
                                    print("User id : \(user["_id"])")
                                }
                            }
                        }

                   }

                    catch let error as NSError
                    {
                        print(error.localizedDescription)
                    }

在这一行中让json =尝试NSJSONSerialization.JSONObjectWithData(_data as!NSData,options:.AllowFragments)as!的NSDictionary 起初我使用" _data"然后Xcode建议更改,它从_data更改为_data! NSData的。

1 个答案:

答案 0 :(得分:3)

你的儿子结构如下 JSON(字典) - >数据(字典) - >用户(字典数组)。首先,您应该从原始json中选择Users数组,然后迭代它。

由于alamofire已经将您的回复序列化,因此无需再次使用JSONSerializer,我正在更新我的回答。

<强>更新 在案例

中尝试此代码
if let DataObject = _data["Data"] as? NSDictionary {
    if let Users = DataObject["Users"] as? [NSDictionary] {
        for user in Users {
            print(user["_id"],user["MembershipDate"],user["FirstName"],user["Email"], separator: "   ", terminator: "\n")
        }
    }
}

完整代码:

Alamofire.request(.GET,App.AppHomeURL() + "Load_Group", parameters: ["groupid":"\(groupId)"]) .responseJSON { response in
        switch response.result {

        case .Success(let _data):
            print(_data)
            if let DataObject = _data["Data"] as? NSDictionary {
                if let Users = DataObject["Users"] as? [NSDictionary] {
                    for user in Users {
                        print(user["_id"],user["MembershipDate"],user["FirstName"],user["Email"], separator: "   ", terminator: "\n")
                    }
                }
            }

        default:
            break;
        }


}