ios - 以不同的方式快速解析 JSON。使用哪一个?

标签 ios json swift

我一直在关注 swift 中的 JSON 解析教程。它具有以下提到的用于解析和检索数据的代码。

func jsonParsingFromURL () {
        let url = NSURL(string: "http://theappguruz.in//Apps/iOS/Temp/json.php")
        let request = NSURLRequest(URL: url!)

        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
            self.startParsing(data!)
        }
    }

    func jsonParsingFromFile()
    {
        let path: NSString = NSBundle.mainBundle().pathForResource("days", ofType: "json")!
        let data : NSData = try! NSData(contentsOfFile: path as String, options: NSDataReadingOptions.DataReadingMapped)

        self.startParsing(data)
    }

    func startParsing(data :NSData)
    {
        let dict: NSDictionary!=(try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary

        for var i = 0 ; i < (dict.valueForKey("MONDAY") as! NSArray).count ; i++
        {
            arrDict.addObject((dict.valueForKey("MONDAY") as! NSArray) .objectAtIndex(i))
        }
        for var i = 0 ; i < (dict.valueForKey("TUESDAY") as! NSArray).count ; i++
        {
            arrDict.addObject((dict.valueForKey("TUESDAY") as! NSArray) .objectAtIndex(i))
        }
        for var i = 0 ; i < (dict.valueForKey("WEDNESDAY") as! NSArray).count ; i++
        {
            arrDict.addObject((dict.valueForKey("WEDNESDAY") as! NSArray) .objectAtIndex(i))
        }
        tvJSON .reloadData()
    }

这很好,但我无法理解线路上发生了什么 -

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
                self.startParsing(data!)

我看到了另一个教程,它使用如下函数来解析 JSON-

//Making the API Request

var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)
//Preparing for the response

//声明一个数组如下

var data: NSMutableData = NSMutableData()

//接收响应

1.

func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
   // Received a new request, clear out the data object
   self.data = NSMutableData()
}
2.

func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
   // Append the received chunk of data to our data object
   self.data.appendData(data)
}
3.

func connectionDidFinishLoading(connection: NSURLConnection!) {
   // Request complete, self.data should now hold the resulting info
   // Convert the retrieved data in to an object through JSON deserialization
   var err: NSError
   var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

   if jsonResult.count>0 && jsonResult["results"].count>0 {
      var results: NSArray = jsonResult["results"] as NSArray
      self.tableData = results
      self.appsTableView.reloadData()

   }
} 

那么以上两种编码有什么区别,建议使用哪一种呢?还请说一下

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
                    self.startParsing(data!)

谢谢!

最佳答案

首先,也是最重要的一点,NSURLConnection 在 iOS 9 中已被弃用。您应该改用 NSURLSession

至于您的问题,它们与异步网络读取有关,而不仅仅是 JSON 解析。

NSURL连接:

NSURLConnection 至少有 2 种不同的使用方式。

  1. 您可以设置委托(delegate)、启动连接,然后等待调用委托(delegate)方法(例如 connection:didReceiveData:)。
  2. 您可以使用类方法sendAsynchronousRequest,它需要一个完成 block 。

sendAsynchronousRequest 方法实现起来更简单,但功能不够强大。在收到所有数据之前,您不会被调用,因此您无法执行诸如显示进度指示器之类的操作,也无法在数据传入时将其保存到磁盘以避免将所有数据保留在内存中。

如果您不需要这些东西,我建议使用基于 block 的 sendAsynchronousRequest 方法。

NSURLSession:

NSURLSessionNSURLConnection 的替代品,也提供基于委托(delegate)和基于 block 的方法,其优点和缺点与 NSURLConnection 类似.

使用NSURLSession,如果您不需要细粒度的控制,那么使用系统的共享 session (NSURLSession.sharedSession())会更容易。然后,使用 NSURLSession 方法 dataTaskWithRequest:completionHandler: 创建一个 NSURLSessionTask,并使用 resume() 方法启动任务运行。就像 NSURLConnection 一样,它会在下载完成时调用完成 block (闭包)。

NSURLSession 还允许您将数据直接下载到磁盘、设置安全连接、在下载时分块获取数据以及许多其他选项(您可能需要或可能不需要) .)

编辑:

以下是 NSURLSession 类引用中有关 sharedSession 的摘录:

  • (NSURLSession *)sharedSession Discussion For basic requests, the URL session class provides a shared singleton session object that gives you a reasonable default behavior. By using the shared session, you can fetch the contents of a URL to memory with just a few lines of code.

Unlike the other session types, you do not create the shared session; you merely request it by calling [NSURLSession sharedSession]. As a result, you don’t provide a delegate or a configuration object. Therefore, with the shared session:

You cannot obtain data incrementally as it arrives from the server.

You cannot significantly customize the default connection behavior.

Your ability to perform authentication is limited.

You cannot perform background downloads or uploads while your app is not running.

The shared session uses the shared NSURLCache, NSHTTPCookieStorage, and NSURLCredentialStorage objects, uses a shared custom networking protocol list (configured with registerClass: and unregisterClass:), and is based on a default configuration.

When working with a shared session, you should generally avoid customizing the cache, cookie storage, or credential storage (unless you are already doing so with NSURLConnection), because there’s a very good chance that you’ll eventually outgrow the capabilities of the default session, at which point you’ll have to rewrite all of those customizations in a manner that works with your custom URL sessions.

In other words, if you’re doing anything with caches, cookies, authentication, or custom networking protocols, you should probably be using a [custom] session instead of the [shared] session.

(我在引用中修正了 Apple 文档中的几个拼写错误。我的更改位于最后一句的方括号中。)

在线搜索 NSURLSession SwiftNSURLSessionDataTask Swift,您应该能够找到有关使用 NSURLSession 的教程。其实很简单。

Alamofire

您还可以搜索“AlamoFire”。它是一个轻量级 Swift 框架,提供轻松的异步下载,包括内置的 JSON 处理。

关于ios - 以不同的方式快速解析 JSON。使用哪一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34021281/

相关文章:

ios - 如何同时录制视频和播放音频(swift教程)

ios - 在 prepareForSegue 的详细 View 中设置属性

iphone - MFI结束了吗?通往Arduino和其他设备的电缆

java - 在java中将嵌套Json文件转换为CSV

ios - 使用 geocoder.geocodeAddressString 添加多个注释(递归?)

ios - Flutter 让 iPhone 上下颠倒

javascript - 如何按名称对四方 field 进行排序(即排序

json - 从具有未知结构 SWIFT 的 JSON 中查找值

ios - 使用 UIAppearance 使 UINavigationBar 具有渐变背景

ios - fetchLimit 返回第一项而不是最后一项