您的位置:首页 > 理论基础 > 计算机网络

网络篇 - 04.网络数据解析(JSON)

2015-08-26 20:58 176 查看

1.网络数据解析概述

由于服务器端返回给我们的数据格式有多种,我们需要将数据转换为我们需要的格式,这里就需要用到数据解析

服务器传输给我们的数据主要有三种:

JSON

XML

二进制数据(图片、视频之类的信息)

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];
// 解析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];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: