Swift-使用NSJSONSerialization生成或解析JSON数据
NSJSONSerialization是iOS5中增加的解析JSON的API. NSJSONSerialization提供了将JSON数据转换为Foundation对象(一般都是NSDictionary和NSArray)和 Foundation对象转换为JSON数据. 在将Foundation对象转换为JSON数据时, 尽量使用NSJSONSerialization.isValidJSONObject先判断能否转换成功,否则容易引起程序崩溃。 注意在Swift2中重新设计了异常处理: > > 在Swift1 中是没有异常处理和抛出机制的,如果要处理异常,要么使用if else语句或switch语句判断处理,要么使用闭包形式的回调函数处理,再要么就使用NSError处理。 > > 在Swift2 中提供了使用throws、throw、try、do、catch这五个关键字组成的异常控制处理机制。 > // // 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |