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 ""
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题