加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

[快速学会Swift第三方库] SwiftyJSON篇

发布时间:2020-12-14 06:57:52 所属栏目:百科 来源:网络整理
导读:[快速学会Swift第三方库] SwiftyJSON篇 SwiftyJSON使得用Swift处理JSON数据更加容易。这是解析JSON字符串封装类。实现功能与Javascript中的JSON.parse相近,使用方便。 目录 快速学会Swift第三方库 SwiftyJSON篇 目录 编码之前 导入SwiftyJSON 其他操作 解析

[快速学会Swift第三方库] SwiftyJSON篇

SwiftyJSON使得用Swift处理JSON数据更加容易。这是解析JSON字符串封装类。实现功能与Javascript中的JSON.parse相近,使用方便。

目录

  • 快速学会Swift第三方库 SwiftyJSON篇
    • 目录
    • 编码之前
      • 导入SwiftyJSON
      • 其他操作
    • 解析本地JSON
      • 示例JSON
      • 示例代码
      • 运行结果
    • 解析网络JSON
      • 示例JSON
      • 示例代码
      • 运行结果
    • 深入学习

编码之前

导入SwiftyJSON

推荐使用CocoaPods进行导入,CocoaPods是一个负责管理iOS项目中第三方开源库的工具,安装CocoaPods之后使用命令行就能轻松地对所有第三方开源库进行安装和更新,而不需要每次上GitHub去下载。
CocoaPods的安装过程传送门:iOS 9 导入类库全面详尽过程(Ruby安装->CocoaPods安装->导入类库)
手动下载:GitHub-SwiftyJSON主页

装好CocoaPods后,修改Podfile文件内容为如下:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios,'9.0'
use_frameworks!

target 'Web' do
pod 'SwiftyJSON',:git => 'https://github.com/SwiftyJSON/SwiftyJSON.git'
end
xcodeproj 'Desktop/Web/Web.xcodeproj'

target后面为工程名,最后一行为工程路径(这里的Web是我的工程名)

再执行命令:

$ pod install

其他操作

在Target->工程名->Build Settings->Search Paths->User Header Search Paths处添加SwiftyJSON所在的目录:

最后在你需要用到SwiftyJSON的类中加上:

import SwiftyJSON

解析本地JSON

示例JSON

创建一个本地文档“Notes.json”用于测试

{"ResultCode":0,"Record":[ {"ID":"1","Date":"2016-5-23","Content":"策划","UserID":"summer"},{"ID":"2","Date":"2016-5-24","Content":"研发",{"ID":"3","Date":"2016-5-25",{"ID":"4","Date":"2016-5-26","Content":"测试",{"ID":"5","Date":"2016-5-27","Content":"发布","UserID":"summer"}]}

示例代码

func jsonFromData() {
        let path = NSBundle.mainBundle().pathForResource("Notes",ofType: "json")!
        let json = JSON(data: NSData(contentsOfFile: path)!)

        //从JSON Dictionary中获取key为ResultCode的int值
        let resultCode = json["ResultCode"].int!
        print("ResultCode:(resultCode)")

        let array = json["Record"]
        //从JSON Array中进行循环解析
        for (index,subJson):(String,JSON) in array {

            let userId = subJson["UserID"].string!
            let content = subJson["Content"].string!
            let date = subJson["Date"].string!

            print("(index):(userId) will do (content) at (date)")
        }
    }

运行结果

ResultCode:0
0:summer will do 策划 at 2016-5-23
1:summer will do 研发 at 2016-5-24
2:summer will do 研发 at 2016-5-25
3:summer will do 测试 at 2016-5-26
4:summer will do 发布 at 2016-5-27

解析网络JSON

示例JSON

这里可以使用Alamofire提供的测试接口

https://httpbin.org/get

在浏览器中打开该地址可以看到:

{
  "args": {},"headers": { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Accept-Encoding": "gzip,deflate,br","Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3","Cache-Control": "max-age=0","Host": "httpbin.org","User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:46.0) Gecko/20100101 Firefox/46.0" },"origin": "202.115.52.205","url": "https://httpbin.org/get" }

示例代码

用苹果自带的NSURLSession进行网络请求,关于网络请求的问题,可以参考Swift学习笔记(3)iOS 9 中的网络请求

func jsonFromNetworking()  {
        var strURL = "https://httpbin.org/get"
        //等价于strURL=strURL.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
        strURL = strURL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet(charactersInString: "`#%^{}"[]|<>").invertedSet)!

        let url = NSURL(string: strURL)!
        let request = NSURLRequest(URL: url)

        let session = NSURLSession.sharedSession()
        let dataTask = session.dataTaskWithRequest(request) { (data,response,error) in
            if (error != nil){
                NSLog("Error:(error?.localizedDescription)")
            }
            else{
                let json = JSON(data: data!)
                //从JSON Dictionary中获取key为headers的JSON Dictionary,再从其中获取key为Host的string值
                let host = json["headers","Host"].string!
                let origin = json["origin"].string!
                print("host:(host),origin:(origin)")
            }
        }
        dataTask.resume()
    }

或者用第三方库Alamofire进行网络请求,关于Alamofire的问题,可以参考[快速学会Swift第三方库] Alamofire篇

func jsonFromNetworkingByAlamofire() {
        Alamofire.request(.GET,"https://httpbin.org/get")
            .responseJSON { (response) in
                switch response.result{
                case .Success:
                    if let value = response.result.value{
                        let json = JSON(value)
                        let host = json["headers","Host"].string!
                        let origin = json["origin"].string!
                        print("host:(host),origin:(origin)")

                    }
                case .Failure(let error):
                    print(error)
                }
        }
    }

运行结果

host:httpbin.org,origin:202.115.52.205

深入学习

这里只列出了最基本的JSON解析方式,如果你希望能够更加深入地学习SwiftyJSON,可以前往GitHub-SwiftyJSON主页 ! 如果你想了解苹果自带的JSON解析方式NSJSONSerialization,可以参考Swift学习笔记(2)网络数据交换格式(XML,JSON)解析

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读