SwiftyJSON的使用祥解

原文出處:鏈接?

GitHub地址

1)比如我們有一個(gè)如下的JSON數(shù)據(jù),表示聯(lián)系人集合:


[? {

?????? "name":"hangge",

??????? "age": 100,

??????? "phones": [

???????????????????????????? {

???????????????????????????????? "name":"公司",

???????????????????????????????? "number":"123456"

???????????????????????????? },

??????????????????????????? {

???????????????????????????????? "name":"家庭",

????????????????????????????????? "number":"001"

??????????????????????????? }

?????????????????????? ]

?? },

{

??????? "name":"big boss",

???????? "age": 1,

????????? "phones": [

????????????????????????????? {

?????????????????????????????????? "name":"公司",

???????????????????????????????????? "number":"111111"

???????????????????????????? }

???????????????????????? ]

??????? }

]



2)使用NSJSONSerializationSwiftyJSON解析

if letuserArray = try ? NSJSONSerialization.JSONObjectWithData( jsonData,

options: .AllowFragments)as? [[String:AnyObject]],

let phones = userArray?[0]["phones"] as ?? [[String:AnyObject]],

let number = phones[0]["number"] as ? String{

?????? // 找到電話號(hào)碼

??????? print("第一個(gè)聯(lián)系人的第一個(gè)電話號(hào)碼:",number)

}

3)使用SwiftyJSON解析:

不用擔(dān)心數(shù)組越界,不用判斷節(jié)點(diǎn),拆包什么的,代碼如下:

let json = JSON(data: jsonData)

if let number = json[0]["phones"][0]["number"].string {

??? // 找到電話號(hào)碼

???? print("第一個(gè)聯(lián)系人的第一個(gè)電話號(hào)碼:",number)

}

3,獲取網(wǎng)絡(luò)數(shù)據(jù),并使用SwiftyJSON解析

(1)與NSURLSession結(jié)合

//創(chuàng)建NSURL對(duì)象

?let urlString:String="http://www.hangge.com/getJsonData.php"

?let url:NSURL! =NSURL(string:urlString)

//創(chuàng)建請(qǐng)求對(duì)象

let request:NSURLRequest=NSURLRequest(URL: url)

let session =NSURLSession.sharedSession()

let dataTask = session.dataTaskWithRequest(request,

completionHandler: {(data, response, error) ->Voidin

if error !=nil{

print(error?.code)

print(error?.description)

}else{

let json =JSON(data: data!)

if let number = json[0]["phones"][0]["number"].string {

// 找到電話號(hào)碼

print("第一個(gè)聯(lián)系人的第一個(gè)電話號(hào)碼:",number)

}

}

})as NSURLSessionTask

//使用resume方法啟動(dòng)任務(wù)

dataTask.resume()

(2)與Alamofire結(jié)合

//創(chuàng)建NSURL對(duì)象

let urlString:String="http://www.hangge.com/getJsonData.php"

let url:NSURL! =NSURL(string:urlString)

Alamofire.request(.GET, url).validate().responseJSON { responsein

switch response.result {

case.Success:

if let value = response.result.value {

let json =JSON(value)

if let number = json[0]["phones"][0]["number"].string {

// 找到電話號(hào)碼

print("第一個(gè)聯(lián)系人的第一個(gè)電話號(hào)碼:",number)

}

}

case.Failure(leterror):

print(error)

}

}

4,獲取值

(1)可選值獲?。∣ptional getter)

通過(guò).number、.string、.bool、.int、.uInt、.float、.double、.array、.dictionary、int8、Uint8、int16、Uint16、int32、Uint32、int64、Uint64等方法獲取到的是可選擇值,我們需要自行判斷是否存在,同時(shí)不存在的話可以獲取具體的錯(cuò)誤信息。

//int

if let age = json[0]["age"].int {

??? print(age)

}else{

?? //打印錯(cuò)誤信息

?? print(json[0]["age"])

}

//String

if let name = json[0]["name"].string {

? print(name)

}else{

? //打印錯(cuò)誤信息

?? print(json[0]["name"])

}

(2)不可選值獲取(Non-optional getter)

使用xxxValue這樣的屬性獲取值,如果沒(méi)獲取到的話會(huì)返回一個(gè)默認(rèn)值。省得我們?cè)倥袛嗖鸢恕?/b>

?? //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[0]["phones"].arrayValue

?? //If not a Dictionary or nil, return [:]

let? phone:Dictionary = json[0]["phones"][0].dictionaryValue

原文出自:www.hangge.com轉(zhuǎn)載請(qǐng)保留原文鏈接:http://www.hangge.com/blog/cache/detail_968.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容