Swift 3 个问题解析 json 响应

Swift 3 problems Parsing json response

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

当我打印 responseString 时,我得到:

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

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

感谢您的帮助

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 ""
    }

在您的代码中将 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 ""
}