1.网络数据解析概述
- 由于服务器端返回给我们的数据格式有多种,我们需要将数据转换为我们需要的格式,这里就需要用到数据解析
- 服务器传输给我们的数据主要有三种:
2.JSON数据概述
- JSON数据是民间版的数据格式,是目前最主流的数据格式,另一种是官方版的数据个数XML
- JSON是一种轻量级的数据格式,一般用于数据交互
- 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];
id objc = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",[objc class]);
}
-(void)JSONNetworkData{
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) {
NSLog(@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",dict);
}];
}
-(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];
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) {
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{
static NSString *identifier = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
NSDictionary *dict = self.videos[indexPath.row];
cell.textLabel.text = dict[@"name"];
cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",dict[@"length"]];
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];
return cell;
}
#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
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];
}