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 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?