JSON解析

JSON是一种数据交换语言,和XML是同样用途的。不过JSON的体积要比XML小,也就意味着在网络传输中速度会比XML更快。

JSON解析方法有几种:1.可以使用第三方框架SBJson,2.使用苹果提供的NSJSONSerialization

首先本地创建一个JSON文件,以便方便使用.

本地创建一个文件名为people.json的json文件,内容如下:

{
    "people":[
        {"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"},
        {"firstName":"Jason","lastName":"Hunter","email":"bbbb"},
        {"firstName":"Elliotte","lastName":"Harold","email":"cccc"}
    ]
}

1.SBJSON

NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"people" ofType:@"json"];
NSString *jsonStr = [[NSString alloc] initWithContentsOfFile:jsonPath encoding:NSUTF8StringEncoding error:nil];
	
//创建一个解析器
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
//进行解析
NSMutableDictionary *dictJson = [jsonParser objectWithString:jsonStr];
	
//将结果写到plist文件中,以便看清楚结构
[dictJson writeToFile:@"/Users/apple/Desktop/abc.plist" atomically:YES];
	
NSArray *array = [dictJson objectForKey:@"people"];
	
for (NSDictionary *dict in array) {
	NSLog(@"firstName : %@",[dict objectForKey:@"firstName"]);
	NSLog(@"email : %@",[dict objectForKey:@"email"]);
}
写到abc.plist文件后,文件层次结构为:

根结构为people的字典,内有3个数组,数组为字典组成,字典中有3个key和value


2.NSJSONSerialization

NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"people" ofType:@"json"];
NSData *data = [NSData dataWithContentsOfFile:jsonPath];
	
NSMutableDictionary *dictJson = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
	
NSArray *array = [dictJson objectForKey:@"people"];
	
for (NSDictionary *dict in array) {
	NSLog(@"firstName : %@",[dict objectForKey:@"firstName"]);
	NSLog(@"email : %@",[dict objectForKey:@"email"]);
}
结果当然跟SBJson的解析结果一样的.


--end


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值