【问题标题】:Can't get specified value from JSON in Swift 3无法从 Swift 3 中的 JSON 获取指定值
【发布时间】:2017-02-07 07:47:12
【问题描述】:

快速解释一下我在做什么,有一个登录屏幕用户输入电子邮件,然后弹出一个验证视图控制器,后端向用户的电子邮件发送验证码,如果用户的电子邮件+验证代码匹配然后他成功登录并且后端以用户的完整信息+唯一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":""}])

身份证没有打印出来,我的错误是什么?

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

更新 1:

我试过下面的代码还是不行,打印语句也没有出来,说明数据是空的||nil,但是如果是这样的话最后一个打印语句是如何打印整个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)")
    }

【问题讨论】:

  • 您将三个“让”测试放入一行/条件中。打破它们以了解它没有通过哪个测试。您的 JSON 是一个顶级数组,包含一个对象字典。所以json 应该是[[String:Any]]。然后从中,您的 ID 应该是 json[0]["BD_Id"]
  • 不相关但在 Swift 3 中将 request 行替换为 var request = URLRequest(url: URL(string: "http://anydomain.com/verif.php")!) 并删除 as URLRequest 演员表。并且两种编码都可以简化为.utf8

标签: ios json swift3


【解决方案1】:

试试这个...你的 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)")
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-13
    • 1970-01-01
    • 2018-01-01
    • 2013-03-02
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多