samedi 27 juin 2015

convert api string to JSON in swift or objective-c

hi i'm getting following string(text/html) not (text/JSON) when make api request.

 let request = NSURLRequest(URL: url!)

    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
    let res =   NSString(data: data, encoding: NSUTF8StringEncoding)!
        var jsonStr = res

        //here 'res' will be {status: 1, userid: "447", store_code: "930"}

        var data = jsonStr.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false)
        var localError: NSError?
        var json: AnyObject! = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &localError)

        println("json res \(json)") // 'json' here is nil

        if let dict = json as? [String: AnyObject] {
             let weather = dict["status"] as? [AnyObject]
                println(weather)

        }

    }

//following is the text/html response from api request

{status: 1, userid: "447", store_code: "930"}

So how can i convert this text/html string to JSON.When i try to use NSJSONSerialization it gave fatal error or nil. Can anybody help me how can i solve this issue in swift or objective-c?

Aucun commentaire:

Enregistrer un commentaire