在Swift 3中读取JSON文件时出错

时间:2023-01-30 22:45:14

I use this code in all my projects in swift 2.2 but when I created new project after updated xcode to xcode 8 I faced this problem in reading JSON file with this code

我在swift 2.2中的所有项目中使用此代码但是当我在更新xcode到xcode 8之后创建新项目时,我在使用此代码读取JSON文件时遇到了这个问题

 do {


        let comURL = "mylinkhere"+"customer_key=\(self.customer_key)"


        // NSLog("PostData: %@",post)

        let regURL:NSURL = NSURL(string: comURL)!


        //let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!

        //let postLength:NSString = String( postData.length )

        let request:NSMutableURLRequest = NSMutableURLRequest(url: regURL as URL)
        request.httpMethod = "POST"
        //request.HTTPBody = postData
        //request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")

        var reponseError: NSError?
        var response: URLResponse?

        var urlData: NSData?

        do {
            urlData = try NSURLConnection.sendSynchronousRequest(request as URLRequest, returning:&response) as NSData?
            // print(urlData)
        } catch let error as NSError {
            reponseError = error
            urlData = nil
        }

        if ( urlData != nil ) {

            let res = response as! HTTPURLResponse!;

            //NSLog("Response code: %ld", res?.statusCode);

            if ((res?.statusCode)! >= 200 && (res?.statusCode)! < 300)
            {
                let responseData:NSString  = NSString(data:urlData! as Data, encoding:String.Encoding.utf8.rawValue)!

                NSLog("Response Data ==> %@", responseData );

                //var error: NSError?

                let jsonData = try JSONSerialization.jsonObject(with: urlData! as Data,  options: .allowFragments) as! [String:AnyObject]




                self.Appstatus = (jsonData as AnyObject).value("android_app_status") as! NSString



               self.StreamURL = (jsonData as AnyObject).value("android_streaming_url") as! NSString

                //[jsonData[@"success"] integerValue];

               // NSLog("App Status2: %@", self.Appstatus);
               // NSLog("App Stream URL2: %@", self.StreamURL);

                if(self.Appstatus == "true")

                {


                }

                else{

                }


            }

        } else {
            let alertView:UIAlertView = UIAlertView()
            alertView.title = "Sign in Failed!"
            alertView.message = "Connection Failure"
            if let error = reponseError {
                alertView.message = (error.localizedDescription)
            }
            alertView.delegate = self
            alertView.addButton(withTitle: "OK")
            alertView.show()
        }

    } catch {
        let alertView:UIAlertView = UIAlertView()
        alertView.title = "Sign Up Failed!"
        alertView.message = "Server Error!"
        alertView.delegate = self
        alertView.addButton(withTitle: "OK")
        alertView.show()
    }

I got the response correctly but the error in these two line when trying to retrieve data from result

我正确地得到了响应但是在尝试从结果中检索数据时这两行中的错误

 self.Appstatus = (jsonData as AnyObject).value("android_app_status") as! NSString


 self.StreamURL = (jsonData as AnyObject).value("android_streaming_url") as! NSString

The error is: 在Swift 3中读取JSON文件时出错

错误是:

2 个解决方案

#1


2  

In Swift 3 most of the AnyObject types has been changed to Any

在Swift 3中,大多数AnyObject类型已更改为Any

Basically in Swift

基本上在斯威夫特

  • do not use valueForKey to get a value for a dictionary key, use key subscription.
  • 不要使用valueForKey来获取字典键的值,请使用键订阅。
  • do not cast types up (as AnyObject) after casting them down (pretty counterproductive).
  • 不要在向下投射类型(如AnyObject)(相当适得其反)。
  • do not use Foundation NSString. Use Swift String.

    不要使用Foundation NSString。使用Swift String。

    let jsonData = try JSONSerialization.jsonObject(with: urlData! as Data,  options: .allowFragments) as! [String:Any]
    self.Appstatus = jsonData["android_app_status"] as! String
    self.StreamURL = jsonData["android_streaming_url"] as! String
    

If the keys are not guaranteed to exist use optional bindings to avoid a runtime error.

如果不保证存在密钥,请使用可选绑定以避免运行时错误。

And finally do not use deprecated synchronous URL loading API.

最后不要使用已弃用的同步URL加载API。

#2


0  

You don't have to typecast your jsonData to AnyObject, which as i can see from your code is a dictionary with type [String:AnyObject]. If you want to unwrap a string from jsonData i suggest you consider the following code.

您不必将jsonData类型转换为AnyObject,正如我从您的代码中看到的那样是一个类型为[String:AnyObject]的字典。如果你想从jsonData解包一个字符串我建议你考虑以下代码。

if let appStatus = jsonData["android_app_status"] as? NSString{
   self.AppStatus = appStatus
}

with this safe unwrapping you can make sure that your program will not crash even if the dictionary dosen't have "android_app_status" key.

使用此安全解包,即使字典没有“android_app_status”键,您也可以确保程序不会崩溃。

Hope this helps.

希望这可以帮助。

#1


2  

In Swift 3 most of the AnyObject types has been changed to Any

在Swift 3中,大多数AnyObject类型已更改为Any

Basically in Swift

基本上在斯威夫特

  • do not use valueForKey to get a value for a dictionary key, use key subscription.
  • 不要使用valueForKey来获取字典键的值,请使用键订阅。
  • do not cast types up (as AnyObject) after casting them down (pretty counterproductive).
  • 不要在向下投射类型(如AnyObject)(相当适得其反)。
  • do not use Foundation NSString. Use Swift String.

    不要使用Foundation NSString。使用Swift String。

    let jsonData = try JSONSerialization.jsonObject(with: urlData! as Data,  options: .allowFragments) as! [String:Any]
    self.Appstatus = jsonData["android_app_status"] as! String
    self.StreamURL = jsonData["android_streaming_url"] as! String
    

If the keys are not guaranteed to exist use optional bindings to avoid a runtime error.

如果不保证存在密钥,请使用可选绑定以避免运行时错误。

And finally do not use deprecated synchronous URL loading API.

最后不要使用已弃用的同步URL加载API。

#2


0  

You don't have to typecast your jsonData to AnyObject, which as i can see from your code is a dictionary with type [String:AnyObject]. If you want to unwrap a string from jsonData i suggest you consider the following code.

您不必将jsonData类型转换为AnyObject,正如我从您的代码中看到的那样是一个类型为[String:AnyObject]的字典。如果你想从jsonData解包一个字符串我建议你考虑以下代码。

if let appStatus = jsonData["android_app_status"] as? NSString{
   self.AppStatus = appStatus
}

with this safe unwrapping you can make sure that your program will not crash even if the dictionary dosen't have "android_app_status" key.

使用此安全解包,即使字典没有“android_app_status”键,您也可以确保程序不会崩溃。

Hope this helps.

希望这可以帮助。