简体   繁体   中英

How to Convert Json response to Swift 3.0, older conversion is throwing Error?

This program is an HTTP connection. How convert ( responcsestring (variable)) to array?

let myUrl = NSURL(string: "http://467.143.211.12/nvn/modules/pm/")
    let requset = NSMutableURLRequest(URL: myUrl!)
    requset.HTTPMethod = "POST"

    let postString = "request=data&from=now&serial=\(p)&password=\(i)&imei=testimei"
    requset.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(requset) {
        data, response, error in

        if error != nil {

            println("eror=\(error)")

            return

        }
        println("responce = \(response)")


        let responcsestring = NSString(data: data, encoding: NSUTF8StringEncoding)

        println("responce data = \(responcsestring)");

When I use this code:

          var error: NSError?
        let jsonData: NSData = data

        let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as! NSDictionary

I am faced with this message:

Could not cast value of type '__NSCFArray' (0x110870650) to 'NSDictionary' (0x1108708d0).

When I refer the solution, the older conversion code using in swift was not working with Swift version 2.0.

var error: NSError?
let jsonData: NSData = data

let jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary

When dealing with JSON, you always convert the original NSData . Don't try converting it to a string and converting that. It's a waste of time, space, and can introduce bugs.

The conversions are in the class NSJSONSerialization . Since NSJSONSerialization doesn't know ahead whether it parses a dictionary or an array, it returns either.

The code in the other reply tried to convert the result to an NSDictionary which obviously fails if you got an array. That's the message that you received. Go back to your basic Swift to look at what as! and as? do to fix this.

But seriously, if you ask for an array and someone posts an answer that tries to give you a dictionary, you should figure out yourself how to adapt that answer. Any answers here are just to get you into the right direction; it's still your responsibility and your code to write.

This is a asynchronous type so use it in do, catch like this . Always try to use asynchronous types when you extract information from a JSON file. Then you can enhance you app's user experience and responsiveness

do {
        let jsonData:AnyObject? = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers)
        if let list = jsonData as? NSArray // or PUT  NSDictionary ( according to your JSON )// 
        {
           // DO YOUR DATA HANDLING 
        }

   } catch let error as NSError {
        print("error")
    } catch {
        // Something else happened.
        // Insert your domain, code, etc. when constructing the error.
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM