简体   繁体   English

如何将 Json 响应转换为 Swift 3.0,较旧的转换会引发错误?

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

This program is an HTTP connection.这个程序是一个 HTTP 连接。 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).无法将“__NSCFArray”(0x110870650)类型的值转换为“NSDictionary”(0x1108708d0)。

When I refer the solution, the older conversion code using in swift was not working with Swift version 2.0.当我参考解决方案时,在 swift 中使用的旧转换代码不适用于 Swift 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 .处理 JSON 时,您总是转换原始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 .转换在类NSJSONSerialization Since NSJSONSerialization doesn't know ahead whether it parses a dictionary or an array, it returns either.由于NSJSONSerialization不知道它是解析字典还是数组,因此它会返回。

The code in the other reply tried to convert the result to an NSDictionary which obviously fails if you got an array.另一个回复中的代码试图将结果转换为NSDictionary ,如果你有一个数组,这显然会失败。 That's the message that you received.这就是你收到的消息。 Go back to your basic Swift to look at what as!回到你的基本 Swift 来看看它是什么as! and as?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 .这是一种异步类型,因此请在 do、catch 中使用它。 Always try to use asynchronous types when you extract information from a JSON file.从 JSON 文件中提取信息时,请始终尝试使用异步类型。 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.
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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