您的位置:首页 > 移动开发 > IOS开发

iOS JSON 数据解析

2015-11-01 21:59 417 查看
JSON 是比较常用的数据格式,相比 XML 层次更清晰,这里介绍两种解析 JSON 的方式:NSJSONSerialization 和 JSONKit

NSJSONSerialization 是 iOS 5 以后推出的,比较好用的 JSON 解析包.

JSON 数据格式由对应的 '[',']' 和 '{','}',前者表示数组,后者表示字典.

NSJSONSerialization 解析过程:

1.获取文件路径

2.获取文件内容

3.解析

简单小例子:

- (IBAction)parserJSON:(id)sender {

//获取文件路径

NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"Student" ofType:@"json"];
NSError *error = nil;
NSData *jsonData = [NSData dataWithContentsOfFile:jsonPath];
NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
if (error == nil) {
NSLog(@"%@",array);
}else {
NSLog(@"%@",error);
}

//数据封装

NSMutableArray *arr = [NSMutableArray array];

for (NSDictionary *dic in array) {
Student *stu = [[Student alloc]initWithDictionary:dic];
[arr addObject:stu];
}

for (Student *stu in arr) {
NSLog(@"%@",stu);
}
}


JSONKit 解析:(代码)

- (IBAction)parserJSONWithJESONKIT:(id)sender {

//获取文件路径

NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"Student" ofType:@"json"];
NSError *error = nil;
NSString *JSONStr = [[NSString alloc]initWithContentsOfFile:jsonPath encoding:NSUTF8StringEncoding error:&error];
NSLog(@"%@",JSONStr);
//让jesonKIT 解析 JSON 数据
NSMutableArray *array = [JSONStr objectFromJSONString];
NSLog(@"%ld",array.count);
//数据封装
NSMutableArray *arr = [NSMutableArray array];

for (NSDictionary *dic in array) {
Student *stu = [[Student alloc]initWithDictionary:dic];
[arr addObject:stu];
}

for (Student *stu in arr) {
NSLog(@"%@",stu);
}
}


JSONKit.zip 下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: