iOS JSON 数据解析
2015-11-01 21:59
417 查看
JSON 是比较常用的数据格式,相比 XML 层次更清晰,这里介绍两种解析 JSON 的方式:NSJSONSerialization 和 JSONKit
NSJSONSerialization 是 iOS 5 以后推出的,比较好用的 JSON 解析包.
JSON 数据格式由对应的 '[',']' 和 '{','}',前者表示数组,后者表示字典.
NSJSONSerialization 解析过程:
1.获取文件路径
2.获取文件内容
3.解析
简单小例子:
JSONKit 解析:(代码)
JSONKit.zip 下载
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 下载
相关文章推荐
- 蓝懿ioS 技术内容和心得交流 11.1 正反向
- 2015 iOS心得八 项目使用自定义的字体
- iOS 动态更新 修复bug jspatch wax总结。
- 零基础ios开发(八 正向和反向传值)
- Git/Framework静态库介绍:创建和使用
- Git/.a静态库的介绍:创建和使用
- iOS之OC基础类和对象
- ios创建自定义控件必须具备的三个方法
- iOS 开发 自定义Tabbar
- 苹果开发 笔记(86)Stack View in xcode 7
- iOS新闻客户端开发教程3--基类编写
- IOS tableView自适应高度
- iOS启动引导页
- IOS Animation动画基础
- #在蓝懿学习iOS的日子#Day9
- ios学习之苹果官方文档的学习(EKCalendarChooserDelegate)
- ios新手必看之手势
- ios学习之苹果官方文档的学习(EKCalendarChooser)
- IOS开发常用英文单词总结
- iOS开发者不可不知的8件事