网络篇 - 04.网络数据解析(JSON)
2015-08-26 20:58
176 查看
1.网络数据解析概述
由于服务器端返回给我们的数据格式有多种,我们需要将数据转换为我们需要的格式,这里就需要用到数据解析服务器传输给我们的数据主要有三种:
JSON
XML
二进制数据(图片、视频之类的信息)
2.JSON数据概述
JSON数据是民间版的数据格式,是目前最主流的数据格式,另一种是官方版的数据个数XMLJSON是一种轻量级的数据格式,一般用于数据交互
JSON的格式很像OC中的字典和数组
{"name" : "jack", "age" : 10} {"names" : ["jack", "rose", "jim"]}
标准JSON格式的注意点:key必须用双引号
要想从JSON中挖掘出具体数据,得对JSON进行解析
我们解析JSON数据就是将其转换为 OC数据类型
JSON和OC对象转换后对应数据类型
{} -> NSDictionary @{}
[] -> NSArray @[]
“jack” -> NSString @”jack”
10 -> NSNumber @10
10.5 -> NSNumber @10.5
true -> NSNumber @1
false -> NSNumber @0
null -> NSNull
3.JSON解析方案
在iOS中,JSON的常见解析方案有4种在iOS中,JSON的常见解析方案有4种
第三方框架:JSONKit、SBJson、TouchJSON(性能从左到右,越差)
苹果原生(自带):NSJSONSerialization(性能最好)
由于苹果自带的JSON解析性能最好,所以我们主要使用的也是苹果原生的解析器
4.JSON解析示例
本地数据解析-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ NSString *json = @"[\"jack\",\"tom\"]"; NSString *json1 = @"null"; // 将字符串转换为二进制数据 NSData *data = [json1 dataUsingEncoding:NSUTF8StringEncoding]; // 解析JSON数据 /* 参数解释: 第一个参数:传入要解析的数据 第二个参数:解析模式 NSJSONReadingMutableContainers = 转换出来的对象是可变数组或者可变字典 NSJSONReadingMutableLeaves = 转换出来的OC对象中的字符串是可变的,注意: iOS7之后无效 bug NSJSONReadingAllowFragments = 如果服务器返回的JSON数据, 不是标准的JSON, 那么就必须使用这个值, 否则无法解析 */ id objc = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; NSLog(@"%@",[objc class]); // 输出结果NSNull }
网络数据解析
// 解析网络数据 -(void)JSONNetworkData{ // 1.获取网络数据 NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=zj&pwd=123it&type=JSON"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { // 2.解析网络数据 // 2.1打印数据,获取数据格式 NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);// 输出结果:{"success":"登录成功"} // 2.2解析数据 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; NSLog(@"%@",dict);// 输出结果:{success = "\U767b\U5f55\U6210\U529f";} }]; }
OC对象转换为JSON数据
-(void)objc2JSON{ NSDictionary *dict = @{ @"name":@"MrRight", @"age":@"25", @"sex":@"Man", }; /* 第一个参数: 需要转换为JSON的对象 第二个参数: 转换为JSON之后是否需要排版 第三个参数: 错误信息 */ NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil]; // 将JSON数据转换为字符串 NSString *temp = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",temp); /* 输出结果: { "name" : "MrRight", "age" : "25", "sex" : "Man" } */ }
5.复杂JSON数据解析
创建UITableViewController一般开发中,正常JSON数据的解析,我们都会创建模型来保存解析后的数据,这里由于获取的数据比较简单,就没有新建模型了
#import "ViewController.h" #import <SDWebImage/UIImageView+WebCache.h> #import <MJRefresh/MJRefresh.h> #import <MediaPlayer/MPMoviePlayerViewController.h> @interface ViewController () @property (nonatomic, strong) NSArray *videos;// 视频信息 @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // 1.获取网络数据 NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/video?type=JSON"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { // 2.解析JSON数据 NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; self.videos = dict[@"videos"]; [self.tableView reloadData]; }]; } #pragma mark - UITableViewDataSource -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return self.videos.count; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ // 1.创建cell static NSString *identifier = @"cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier]; // 2.设置cell的数据 NSDictionary *dict = self.videos[indexPath.row]; cell.textLabel.text = dict[@"name"]; cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",dict[@"length"]]; // 2.1 缓存并下载图片 NSString *urlStr =[NSString stringWithFormat:@"http://120.25.226.186:32812/%@", dict[@"image"]]; urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:urlStr]; [cell.imageView sd_setImageWithURL:url placeholderImage:nil]; // 3.返回cell return cell; } #pragma mark - UITableViewDelegate // 选中某一行后播放视频 -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ // 获取视频URL NSDictionary *dict = self.videos[indexPath.row]; NSString *urlStr =[NSString stringWithFormat:@"http://120.25.226.186:32812/%@", dict[@"url"]]; urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:urlStr]; // 加载视频播放控制器 MPMoviePlayerViewController *vc = [[MPMoviePlayerViewController alloc] initWithContentURL:url]; // 显示控制器 [self presentViewController:vc animated:YES completion:nil]; }
相关文章推荐
- 网络篇 - 02.NSURLConnection基本使用
- 网络篇 - 01.网络编程概述
- 网络方面的面试题
- TCP/IP详解 卷I:协议 の校验和
- TCP/IP详解 卷I:协议 のUDP 用户数据包协议
- 计算机网络面试题2
- 计算机网络面试题1
- 常见HTTP错误代码大全
- http头需知
- HttpClient 4.3教程
- http Cache-Control: If-None-Match ETag/If-Modifed-Since Last-Modified
- BZOJ 1491 [NOI2007]社交网络
- Android之Http,Socket和Tcp/Ip
- HttpServletRequest常用获取URL的方法
- Http请求与响应
- HTTP返回代码 201 304 404 500等代表的含义
- Linux的PXE kickstart网络自动装机
- (三) HTTP/2的帧
- AngularJS中的$http.post与jQuery.post的区别
- 贝叶斯网络