iOS 数据交换格式-JSON

JSON常用编码/解码框架

(1)SBJson,支持ARC
(2)TouchJSON,支持ARC和MRC
(3)YAJL,基于SBJson进行了优化,底层API使用C编写,上层API使用ObjectiveC编写,不支持ARC
(4)JSONKit,不支持ARC
(5)NextiveJson,不支持ARC
(6)NSJSONSerialization,支持ARC,iOS5以后已经包含在SDK中,无需额外安装。
ARC说明,转载:https://www.jianshu.com/p/b13983e341fd
http://www.cocoachina.com/articles/19109

NSJSONSerialization

使用NSJSONSerialization的类方法JSONObjectWithData:options:error:进行解码,其中options参数指定了解析JSON的模式,该参数是美剧类型NSJSONReadingOptions定义的,共有如下3个常量:
**(1)NSJSONReadingMutableContainers,**指定解压返回的是可变数组或字典,如果以后需要修改结果,这个常量是合适的选择,Swift是mutableContainers。
**(2)NSJSONReadingMutableLeaves,**指定叶节点是可变字符串。swift是MutableLeaves。
**(3)NSJSONReadingAllowFragments,**允许解析器可以解析那些不是JSON数组或字典的JSON数据片段,如123、"ABC"等。swift是AllowFragment。
例:
Swift代码

// An highlighted block
override func viewDidLoad(){
	super.viewDidLoad()
	let path=Bundle.main.path(forResource:"Notes",ofType:"json")!
	let jsonData=try! Data(contentsOf:URL(fileURLWithPath:path))
	do{
		let jsonObj=try JSONSerialization.jsonObject(with:jsonData,options:.mutableContainers) as! NSDictionary
		self.listData=jsonObj["Record"] as! [[String:String]]
	}catch{
		NSLog("解码失败")
	}
}

ObjectiveC代码

// An highlighted block
_(void)viewDidLoad{
	[super viewDidLoad];
	NSString *path=[[NSBundle mainBundle] pathForResource:@"Notes" ofType:@"json"];
	NSData *jsonData=[[NSData alloc] initWithContentsOfFile:path];
	NSError *error;
	id jsonObj=[NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
	if(!jsonObj || error){
		NSLog(@"解码错误");
	}
	self.listData=jsonObj[@"Record"];
}

参考资料
《IOS开发指南 从HELLO WORLD到APP STORE上架 第5版》

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值