Swift開發之SwiftyJSON的使用祥解(附範例,用於JSON資料處理)

來源:互聯網
上載者:User

1,SwiftyJSON介紹與配置
SwiftyJSON是個使用Swift語言編寫的開源庫,可以讓我們很方便地處理JSON資料(解析資料、產生資料)。
GitHub地址:https://github.com/SwiftyJSON/SwiftyJSON
使用配置:直接 SwiftyJSON.swift 添加到項目中即可。 

2,SwiftyJSON的優點
同 NSJSONSerializationSwiftyJSON 相比,在擷取多階層的JSON資料時。SwiftyJSON不需要一直判斷這個節點是否存在,是不是我們想要的class,下一個節點是否存在,是不是我們想要的class…。同時,SwiftyJSON內部會自動對optional(可選類型)進行拆包(Wrapping ),大大簡化了代碼。

(1)比如我們有一個如下的JSON資料,表示連絡人集合:


[
    {
        "name": "hangge",
        "age": 100,
        "phones": [
            {
                "name": "公司",
                "number": "123456"
            },
            {
                "name": "家庭",
                "number": "001"
            }
        ]
    },
    {
        "name": "big boss",
        "age": 1,
        "phones": [
            {
                "name": "公司",
                "number": "111111"
            }
        ]
    }
]

為便於測試比較,我們先將JSON格式的字串轉為NSData:


let jsonStr = "[{\"name\": \"hangge\", \"age\": 100, \"phones\": [{\"name\": \"公司\",\"number\": \"123456\"}, {\"name\": \"家庭\",\"number\": \"001\"}]}, {\"name\": \"big boss\",\"age\": 1,\"phones\": [{ \"name\": \"公司\",\"number\": \"111111\"}]}]"
 
if let jsonData = jsonStr.dataUsingEncoding(NSUTF8StringEncoding,
    allowLossyConversion: false) {
    //.........
}

(2)使用NSJSONSerializationSwiftyJSON解析

比如我們要取第一條連絡人的第一個電話號碼,每個層級都判斷就很麻煩,代碼如下:


if let userArray = try? NSJSONSerialization.JSONObjectWithData(jsonData,
    options: .AllowFragments) as? [[String: AnyObject]],
    let phones = userArray?[0]["phones"] as? [[String: AnyObject]],
    let number = phones[0]["number"] as? String {
        // 找到電話號碼
        print("第一個連絡人的第一個電話號碼:",number)
}

即使使用optional來簡化一下,代碼也不少:


if let userArray = try? NSJSONSerialization.JSONObjectWithData(jsonData,
    options: .AllowFragments) as? [[String: AnyObject]],
    let number = (userArray?[0]["phones"] as? [[String: AnyObject]])?[0]["number"]
        as? String {
        // 找到電話號碼
        print("第一個連絡人的第一個電話號碼:",number)
}

(3)使用SwiftyJSON解析:
不用擔心數組越界,不用判斷節點,拆包什麼的,代碼如下:


let json = JSON(data: jsonData)
if let number = json[0]["phones"][0]["number"].string {
    // 找到電話號碼
    print("第一個連絡人的第一個電話號碼:",number)
}

如果沒取到值,還可以走到錯誤處理來了,列印一下看看錯在哪:


let json = JSON(data: jsonData)
if let number = json[0]["phones"][0]["number"].string {
    // 找到電話號碼
    print("第一個連絡人的第一個電話號碼:",number)
}else {
    // 列印錯誤資訊
    print(json[0]["phones"][0]["number"])
}

3,擷取網路資料,並使用SwiftyJSON解析

除瞭解析本地的JSON資料,我們其實更常通過url地址擷取遠端資料並解析。
(1)與NSURLSession結合


//建立NSURL對象
let urlString:String="http://www.111cn.net /getJsonData.php"
let url:NSURL! = NSURL(string:urlString)
//建立請求對象
let request:NSURLRequest = NSURLRequest(URL: url)
 
let session = NSURLSession.sharedSession()
 
let dataTask = session.dataTaskWithRequest(request,
    completionHandler: {(data, response, error) -> Void in
        if error != nil{
            print(error?.code)
            print(error?.description)
        }else{
            let json = JSON(data: data!)
            if let number = json[0]["phones"][0]["number"].string {
                // 找到電話號碼
                print("第一個連絡人的第一個電話號碼:",number)
            }
        }
}) as NSURLSessionTask
 
//使用resume方法啟動任務
dataTask.resume()

(2)與Alamofire結合


//建立NSURL對象
let urlString:String="http://www.111cn.net /code/test.php"
let url:NSURL! = NSURL(string:urlString)
 
Alamofire.request(.GET, url).validate().responseJSON { response in
    switch response.result {
    case .Success:
        if let value = response.result.value {
            let json = JSON(value)
            if let number = json[0]["phones"][0]["number"].string {
                // 找到電話號碼
                print("第一個連絡人的第一個電話號碼:",number)
            }
        }
    case .Failure(let error):
        print(error)
    }
}

4,擷取值
(1)可選值擷取(Optional getter)
通過.number、.string、.bool、.int、.uInt、.float、.double、.array、.dictionary、int8、Uint8、int16、Uint16、int32、Uint32、int64、Uint64等方法擷取到的是可選擇值,我們需要自行判斷是否存在,同時不存在的話可以擷取具體的錯誤資訊。


//int
if let age = json[0]["age"].int {
    print(age)
} else {
    //列印錯誤資訊
    print(json[0]["age"])
}
    
//String
if let name = json[0]["name"].string {
    print(name)
} else {
    //列印錯誤資訊
    print(json[0]["name"])
}

(2)不可選值擷取(Non-optional getter)
使用 xxxValue 這樣的屬性擷取值,如果沒擷取到的話會返回一個預設值。省得我們再判斷拆包了。


//If not a Number or nil, return 0
let age: Int = json[0]["age"].intValue
 
//If not a String or nil, return ""
let name: String = json[0]["name"].stringValue
 
//If not a Array or nil, return []
let list: Array<JSON> = json[0]["phones"].arrayValue
 
//If not a Dictionary or nil, return [:]
let phone: Dictionary<String, JSON> = json[0]["phones"][0].dictionaryValue

(3)擷取未經處理資料(Raw object)


let jsonObject: AnyObject = json.object
 
if let jsonObject: AnyObject = json.rawValue
 
//JSON轉化為NSData
if let data = json.rawData() {
    //Do something you want
}
 
//JSON轉化為String字串
if let string = json.rawString() {
    //Do something you want
}

5,設定值


json[0]["age"].int =  101
json[0]["name"].string =  "111cn.net "
json[0]["phones"].arrayObject = [["name":"固話", "number":110],["name":"手機", "number":120]]
json[0]["phones"][0].dictionaryObject = ["name":"固話", "number":100]

6,下標訪問(Subscript)
可以通過數字、字串、數群組類型的下標訪問JSON資料的層級與屬性。比如下面三種方式的結果都是一樣的:


//方式1
let number = json[0]["phones"][0]["number"].stringValue
    
//方式2
let number = json[0,"phones",0,"number"].stringValue
    
//方式3
let keys:[JSONSubscriptType] = [0,"phones",0,"number"]
let number = json[keys].stringValue

7,迴圈遍曆JSON對象中的所有資料
(1)如果JSON資料是數群組類型(Array)


for (index,subJson):(String, JSON) in json {
    print("\(index):\(subJson)")
}

(2)如果JSON資料是字典類型(Dictionary)


for (key,subJson):(String, JSON) in json[0] {
    print("\(key):\(subJson)")
}

8,構造建立JSON對象資料
(1)空的JSON對象

let json: JSON =  nil

(2)使用簡單的資料類型建立JSON對象


//StringLiteralConvertible
let json: JSON = "I'm a son"
 
//IntegerLiteralConvertible
let json: JSON =  12345
 
//BooleanLiteralConvertible
let json: JSON =  true
 
//FloatLiteralConvertible
let json: JSON =  2.8765

(3)使用數組或字典資料建立JSON對象

//DictionaryLiteralConvertible
let json: JSON =  ["I":"am", "a":"son"]
 
//ArrayLiteralConvertible
let json: JSON =  ["I", "am", "a", "son"]
 
//Array & Dictionary
var json: JSON =  ["name": "Jack", "age": 25, "list": ["a", "b", "c", ["what": "this"]]]
json["list"][3]["what"] = "that"
json["list",3,"what"] = "that"
let path = ["list",3,"what"]
json[path] = "that"

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.