中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

IOS中用NSJSONSerialization來實(shí)現(xiàn)對(duì)JSON格式的解析

2018-07-20    來源:open-open

容器云強(qiáng)勢(shì)上線!快速搭建集群,上萬Linux鏡像隨意使用
   IOS中對(duì)JSON格式的解析通?梢圆捎肗SJSONSerialization來實(shí)現(xiàn). 

如,我們可以用個(gè)簡答的HTTP請(qǐng)求的方式獲取JSON數(shù)據(jù),(以下都是在playground中寫的)

    var url = "http://0.0.0.0:8000" 

    // 返回?cái)?shù)據(jù)為{"status": 0, "data": [{"hello": "world"}, {"try": "again"}]}

var content = NSString(contentsOfURL:NSURL(string:url)!, encoding:NSUTF8StringEncoding, error:nil)

// 在解析之前,要先將json格式的數(shù)據(jù)內(nèi)容轉(zhuǎn)換成NSData的格式,

var data: NSData = content!.dataUsingEncoding(NSUTF8StringEncoding)!

然后,解析過程也非常簡單.

    var json  = NSJSONSerialization.JSONObjectWithData(data, 

        options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

    json["status"]  // 0, 獲取其中的元素

    let aray = json["data"] as NSArray

    array[0]["hello"] // world

需要注意的是,對(duì)于字符串的數(shù)據(jù)(網(wǎng)絡(luò)請(qǐng)求大多都是字符串類型),一定要先轉(zhuǎn)換成NSData格式,才能使用NSJSONSerialization來解析.


對(duì)于JSON的解析和操作,也可以使用另一個(gè)JSON類庫https://github.com/SwiftyJSON/SwiftyJSON.

使用方法非常簡單:

let json = JSON(data: dataFromNetworking)

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

// Now you got your value

}

上邊的.string可以自動(dòng)對(duì)可選型進(jìn)行解包.類似的還有.int, .bool, .number等.

如果是非可選型,則直接使用.intValue, .stringValue, .arrayValue, .dictionaryValue即可,如

let id: Int = json["id"].intValue

let name: String = json["name"].stringValue

let list: Array<JSON> = json["list"].arrayValue

let user: Dictionary<String, JSON> = json["user"].dictionaryValue


如果json是一個(gè)字典或者數(shù)組,需要做遍歷操作呢,

for (key: String, subJson: JSON) in json { // Do something you want }

for (index: String, subJson: JSON) in json { // Do something you want }


將數(shù)據(jù)存儲(chǔ)為JSON格式:

json["name"] = JSON("newName")

json[0] = JSON(1)

json["id"].int = 123

json["coordinate"].double = 123.456

json["name"].string = "newString"

json.array = [1, 2, 3, 4]

json.dictionary = ["name": "newName", "age": 20]


獲取raw數(shù)據(jù)的方式:

let jsonObject: AnyObject = json.object

let jsonObject: AnyObject = json.rawValue

let data = json.rawData()

let string = json.rawString()


標(biāo)簽: 網(wǎng)絡(luò)

版權(quán)申明:本站文章部分自網(wǎng)絡(luò),如有侵權(quán),請(qǐng)聯(lián)系:west999com@outlook.com
特別注意:本站所有轉(zhuǎn)載文章言論不代表本站觀點(diǎn)!
本站所提供的圖片等素材,版權(quán)歸原作者所有,如需使用,請(qǐng)與原作者聯(lián)系。

上一篇:jQuery多選框的全選、全不選、反選

下一篇:C#封裝好的Ftp客戶端代碼類