无法从Swift 3中的JSON获取指定值

时间:2017-02-07 07:47:13

标签: ios json swift3

快速解释我正在做什么,有登录屏幕用户输入电子邮件,然后弹出验证viewController,后端会向用户的电子邮件发送验证码,如果用户的电子邮件+验证码匹配,然后他成功登录,后端使用用户的完整信息+唯一ID进行回复。 所以我想单独获取该唯一ID。

我的验证视图控制器代码:

@IBAction func doneBtnPressed(_ sender: Any) {

    let request = NSMutableURLRequest(url: NSURL(string: "http://anydomain.com/verif.php")! as URL)
    request.httpMethod = "POST"
    let postString = "bdemail=\(bdEmail)&verifcode=\(verifyCodeTxtField.text!)"
    request.httpBody = postString.data(using: String.Encoding.utf8)

    let task = URLSession.shared.dataTask(with: request as URLRequest) {
        data, response, error in

        if error != nil {
            print("error=\(error)")
            return
        }else {
            do {
                if let data = data,
                    let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
                    let users = json["BD_Id"] as? [[String: Any]] {
                    print(users)
                }
            } catch {
                print("Error deserializing JSON: \(error)")
            }
        }

        print("response = \(response)")

        let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        print("responseString = \(responseString)")
    }

    task.resume()

    self.performSegue(withIdentifier: "mySegueIdentifier", sender: nil)

}

但我只收到完整的回复,我希望获得唯一ID - > " BD_Id"单独,所以我可以存储它在我的应用程序中使用它。

以下是回复:

    { URL: http://anydomain.com/verif.php } { status code: 200, headers {
    Connection = "Keep-Alive";
    "Content-Type" = "text/html; charset=UTF-8";
    Date = "Tue, 07 Feb 2017 07:40:00 GMT";
    Server = Apache;
    "Transfer-Encoding" = Identity;
} })


responseString = Optional(  [{"Rcode":101,"BD_Id":"8","BD_Name":"","BD_Email":"email@domain.com","BD_Country":"","BD_Home_Lat":"","BD_Home_Lon":"","BD_BT":"","BD_RH":"","BD_DOB":"0000-00-00","BD_Mobile":"","BD_Last_Donation":"0000-00-00","BD_Token":""}])

ID没有打印出来,所以我的错误是什么?

提前致谢。请注意,我是Swift Networking的初学者,这是我第一次处理JSON。

更新1:

我已经尝试过以下代码,但仍然没有工作,并且print语句没有出来,这意味着数据为空|| nil,但是如果是这样那么最后的print语句怎么样打印整个JSON脚本!

let task = URLSession.shared.dataTask(with: request as URLRequest) {
        data, response, error in

        if error != nil {
            print("error=\(error)")
            return
        }else {
            do {
                if data != nil {
                    print("Hello from the inside...")
                    let json = try JSONSerialization.jsonObject(with: data!) as? [[String: Any]]
                    for obj in json! {
                        if let bdId = obj["BD_Id"] as? String {
                            print(bdId)
                        } 
                    }
                }
            } catch {
                print("Error deserializing JSON: \(error)")
            }
        }

        print("response = \(response)")

        let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        print("responseString = \(responseString)")
    }

1 个答案:

答案 0 :(得分:2)

试试这个...你的JSON是字典数组.. [[String:Any]]

  do{
         let json = try JSONSerialization.jsonObject(with: data!, options:[]) as! [[String:Any]]
          for obj in json {
               if let bdId = obj["BD_Id"] as? String {
                   print(bdId)
               } 
          }
  }
  catch {
      print("Error with Json: \(error)")
  }