dt4233 2016-08-13 14:19
浏览 82
已采纳

Swift 3问题解析json响应

I am new on Swift but I was follwoing some examples like how to make a login app sending username and password fields to a php file and getting the json response back.

When I print my responseString I get:

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

But when I try to parse the json I never can set the username variable because never gets into that part of the code, I just get "here"

Thanks for the help

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 ""
    }
  • 写回答

1条回答 默认 最新

  • doubian19900911 2016-08-13 15:31
    关注

    Change the NSDictionary to NSArray in your code because you are getting an array and trying to convert to dictonary:

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

    get the object at index 0 which will give you dictonary & then you can get username

    So the Final code will be:

    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 ""
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Converting circular structure to JSON
  • ¥30 Hyper-v虚拟机相关问题,求解答。
  • ¥15 TSM320F2808PZA芯片 Bootloader
  • ¥45 谷歌浏览器出现开发者工具无法显示已创建的,但您可以调试已部署的代码。 状态代码 404, net::ERR HTTP RESPONSE CODE FAILURE
  • ¥15 如何解决蓝牙通话音频突发失真问题
  • ¥15 安装opengauss数据库报错
  • ¥15 【急】在线问答CNC雕刻机的电子电路与编程
  • ¥60 在mc68335芯片上移植ucos ii 的成功工程文件
  • ¥15 笔记本外接显示器正常,但是笔记本屏幕黑屏
  • ¥15 Python pandas