swift_036(Swift之第三方库SwiftyJSON篇)

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

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

目录

其他操作

在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":"研发","UserID":"summer"},
{"ID":"3","Date":"2016-5-25","Content":"研发","UserID":"summer"},
{"ID":"4","Date":"2016-5-26","Content":"测试","UserID":"summer"},
{"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)
                }
        }
    }
  
  
  • 1

运行结果

host:httpbin.org,origin:202.115.52.205
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值