NSJSONSerialization是iOS5中增長的解析JSON的API.php
NSJSONSerialization提供了將JSON數據轉換爲Foundation對象(通常都是NSDictionary和NSArray)和 Foundation對象轉換爲JSON數據.html
在將Foundation對象轉換爲JSON數據時, 儘可能使用NSJSONSerialization.isValidJSONObject先判斷可否轉換成功,不然容易引發程序崩潰。json
注意在Swift2中從新設計了異常處理:swift
在Swift1 中是沒有異常處理和拋出機制的,若是要處理異常,要麼使用if else語句或switch語句判斷處理,要麼使用閉包形式的回調函數處理,再要麼就使用NSError處理。閉包
在Swift2 中提供了使用throws、throw、try、do、catch這五個關鍵字組成的異常控制處理機制。ide
// // ViewController.swift // testJSON // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //調用testJsonData函數 testJsonData() } //定義函數 testJsonData() func testJsonData() { //定義個集合結構(字典) let userData = [ "uname": "張三", "tel": [ "mobile": "13811223344", "home": "010-65384706" ], "age": 20 ] //1.判斷能不能轉換JSON數據 if (!NSJSONSerialization.isValidJSONObject(userData)) { print("1.userData: invalid json object") return } else { print("1.userData: valid json object") } //2.利用OC的json庫轉換成OC的NSData, //若是設置options爲NSJSONWritingOptions.PrettyPrinted,則打印格式更好閱讀 //先前的語法,Xcode7中報錯: Extra argument ‘error’ in call //let data : NSData! = NSJSONSerialization.dataWithJSONObject(user, options: nil, error: nil) //在Swift2中的語法: let data: NSData! = try? NSJSONSerialization.dataWithJSONObject(userData, options: []) //NSData轉換成NSString打印輸出 let str = NSString(data:data, encoding: NSUTF8StringEncoding) //輸出json字符串 print("2.Json Str: \(str)") //3.把NSData對象轉換回JSON對象 //let jsonData : AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.AllowFragments, error:nil) //在Swift2中的語法: let jsonData = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) print("3.Json Object: \(jsonData)"); //4.獲取JSON對象中的值 let uname : AnyObject = jsonData!.objectForKey("uname")! let mobile : AnyObject = jsonData!.objectForKey("tel")!.objectForKey("mobile")! let age : AnyObject = jsonData!.objectForKey("age")! print("4:get Json Object:"); print("uname: \(uname)") print("mobile: \(mobile)") print("age: \(age)") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
參考:函數
http://www.hangge.com/blog/cache/detail_647.html
http://www.cocoachina.com/bbs/read.php?tid-270783.html
http://www.csdn.net/article/2015-07-01/2825095/2
http://www.cocoachina.com/swift/20150623/12231.html.net