【问题标题】:Swift 3 problems Parsing json responseSwift 3 解析 json 响应的问题
【发布时间】:2016-08-13 14:19:13
【问题描述】:

我是 Swift 的新手,但我正在学习一些示例,例如如何制作登录应用程序,将用户名和密码字段发送到 php 文件并返回 json 响应。

当我打印我的 responseString 时,我得到:

[{"userid":1,"username":"rodrigo","password":"minhoca","groupname":"couple"}]

但是当我尝试解析 json 时,我永远无法设置用户名变量,因为永远不会进入代码的那部分,我只是得到“这里”

感谢您的帮助

func sendLoginInfo(username: String, password: String) -> String{
        if let url = URL(string: "myphpurl"){
            let request = NSMutableURLRequest(url:url)
            request.httpMethod = "POST";// Compose a query string
            let postString = "?username=\(myUsername)&password=\(myPassword)"
            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("1\(error)")
                }
                else{
                    let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                  print("response string = \(responseString!)")
                }

                do {

                    if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary {

                        // Print out dictionary
                        print(convertedJsonIntoDict)

                        // Get value by key
                        let firstNameValue = convertedJsonIntoDict["username"] as? String
                        print("here = \(firstNameValue!)")

                    }
                    else{
                         print("here")
                    }
                } catch let error as NSError {
                    print(error.localizedDescription)
                }
            }
            task.resume()
        }
        return ""
    }

【问题讨论】:

    标签: php json xcode swift3


    【解决方案1】:

    在您的代码中将 NSDictionary 更改为 NSArray,因为您正在获取一个数组并尝试转换为字典:

     if let convertedJson = try JSONSerialization.jsonObject(with: data!, options: []) as? NSArray 
    

    在索引 0 处获取对象,这将为您提供字典,然后您可以获得用户名

    所以最终代码是:

    func sendLoginInfo(username: String, password: String) -> String{
        if let url = URL(string: "myphpurl"){
            let request = NSMutableURLRequest(url:url)
            request.httpMethod = "POST";// Compose a query string
            let postString = "?username=\(myUsername)&password=\(myPassword)"
            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("1\(error)")
                }
                else{
                    let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                  print("response string = \(responseString!)")
                }
    
                do {
    
                    if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSArray {
    
                        // Print out dictionary
                        print(convertedJsonIntoDict)
    
                        // Get value by key
                        let firstNameValue = (convertedJsonIntoDict[0] as! NSDictionary)["username"] as? String
                        print("here = \(firstNameValue!)")
    
                    }
                    else{
                         print("here")
                    }
                } catch let error as NSError {
                    print(error.localizedDescription)
                }
            }
            task.resume()
        }
        return ""
    }
    

    【讨论】:

    • 谢谢,但现在它给了我:使用未声明的类型 NSDictionary
    • 对不起,我在代码中打错了字。再次尝试此代码,我已对其进行了编辑。我拼错了关键字,它是 NSDictionary
    猜你喜欢
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    相关资源
    最近更新 更多