在Swift 2中解析JSON数据

时间:2022-02-22 15:34:03

I am parsing the data and I am getting the responseString also.But my problem is I want to convert it into dictionary and then I want to get the values from that jsonObject. But I am unable to get that.

我正在解析数据,我也得到了responseString。但我的问题是我想将它转换为字典然后我想从那个jsonObject获取值。但我无法做到这一点。

My Code is as follows

我的守则如下

 func loginRequest(url:String, withParams params: [String: String?], postCompleted : (succeeded: Bool, msg: String) -> ()){

        let request = NSMutableURLRequest(URL: NSURL(string: url)!)

        let session = NSURLSession.sharedSession()

        request.HTTPMethod = "POST"



        var err: NSError?

        var bodyData = ""

        for (key,value) in params{

            if (value == nil){ continue }

            let scapedKey = key.stringByAddingPercentEncodingWithAllowedCharacters(

                .URLHostAllowedCharacterSet())!

            let scapedValue = value!.stringByAddingPercentEncodingWithAllowedCharacters(

                .URLHostAllowedCharacterSet())!

            bodyData += "\(scapedKey)=\(scapedValue)&"

        }



        request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)



        let task = session.dataTaskWithRequest(request,

            completionHandler: {data, response, error -> Void in

                let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)

                postCompleted(succeeded: true, msg: dataString! as String)

                print(dataString!)



                if let datas = dataString!.dataUsingEncoding(NSUTF8StringEncoding) {



                    do{

                        let json = try NSJSONSerialization.JSONObjectWithData(datas, options: []) as? [String:AnyObject]

                        //return json

                        print(json)

                    }

                    catch

                    {

                         print("Something went wrong")

                    }



                }





                          })



        task.resume()

    }

I am calling that method like this

我这样称呼这个方法

self.loginRequest("http://stream.gsr-india.com:8080/pgn_service/REST/WebService/GetUserDetails",

                withParams: ["first_name":firstNameTextField.text,"last_name":lastNameTextField.text , "application_id":uniqueIdTextField.text])

                {

                    (succeeded: Bool, msg: String) -> () in

                    if(succeeded) {

                        if msg == "0"

                        {

                            //Incorrect data...

                        }

                        else

                        {

                            //The login it's ok...



                        }

                    }

            }

Can anyone Please help me to resolve that. Thanks In Advance.

任何人都可以帮我解决这个问题。提前致谢。

1 个解决方案

#1


1  

Change method declaration to

将方法声明更改为

 func loginRequest(url:String, withParams params: [String: String?], postCompleted : (succeeded: Bool, msg: NSDictionary?) -> ()){

then change the task handler to

然后将任务处理程序更改为

let task = session.dataTaskWithRequest(request,

    completionHandler: {data, response, error -> Void in

        let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
      print(dataString!)
           do{
               let json = try NSJSONSerialization.JSONObjectWithData(datas, options: []) as? [String:AnyObject]
               postCompleted(succeeded: true, msg: json)
                print(json)
           }
           catch {
                print("Something went wrong")
           }
       }
     })

change the callback to

将回调更改为

        (succeeded: Bool, msgDict: NSDictionary?) -> () in
                   if let dict =  msgDict {
                      // call any value like dict["error"] etc
                   }

#1


1  

Change method declaration to

将方法声明更改为

 func loginRequest(url:String, withParams params: [String: String?], postCompleted : (succeeded: Bool, msg: NSDictionary?) -> ()){

then change the task handler to

然后将任务处理程序更改为

let task = session.dataTaskWithRequest(request,

    completionHandler: {data, response, error -> Void in

        let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
      print(dataString!)
           do{
               let json = try NSJSONSerialization.JSONObjectWithData(datas, options: []) as? [String:AnyObject]
               postCompleted(succeeded: true, msg: json)
                print(json)
           }
           catch {
                print("Something went wrong")
           }
       }
     })

change the callback to

将回调更改为

        (succeeded: Bool, msgDict: NSDictionary?) -> () in
                   if let dict =  msgDict {
                      // call any value like dict["error"] etc
                   }