1、JSON认识
- 什么是json
- JSON是一种轻量级的数据格式,一般用于数据交互
- 服务器返回给客户端的数据,一般都是JSON格式或者XML格式(文件下载除外)
- 1.2 注意点
- 标准JSON格式的注意点:
key必须用双引号
JSON解析方案
- 在iOS中,JSON的常见解析方案有
4种
- 第三方框架:JSONKit、SBJson、TouchJSON(性能从左到右,越差)
- 苹果原生(自带):NSJSONSerialization(
性能最好
)- NSJSONSerialization的常见方法
// JSON数据 -> OC对象
+ (id)JSONObjectWithData:(NSData*)data options:(NSJSONReadingOptions)opt error:(NSError**)error;
// OC对象 -> JSON数据
+ (NSData*)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError**)error;
2、JSON — OC相互转换
- JSON和OC对象转换后对应数据类型
JSON和OC对象转换.png
{} -> NSDictionary @{}
[] -> NSArray @[]
"jack" -> NSString @"jack"
10 -> NSNumber @10
10.5 -> NSNumber @10.5
true -> NSNumber @1
false -> NSNumber @0
null -> NSNull
// 利用NSJSONSerialization类
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;
// 例如将json转换成OC字典
/*
第一个参数: 需要转换的json数据
第二个参数: 告诉系统如何转换json数据(转换出来的对象是否可变/子对象是否课变/是否是标准json)
NSJSONReadingMutableContainers = 转换出来的对象是可变数组或者可变字典
NSJSONReadingMutableLeaves = 转换出来的OC对象中的字符串是可变的 \ 注意: iOS7之后无效 bug
NSJSONReadingAllowFragments = 如果服务器返回的JSON数据, 不是标准的JSON, 那么就必须使用这个值, 否则无法解析,允许解析出来的对象不是字典或者数组,比如直接是字符串或者NSNumber,比如直接是字符串或者NSNumber :{15}, {"abc"}
第三个参数: 错误信息
*/
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
4、OC对象 -> JSON数据(NSData)
// 利用NSJSONSerialization类
+ (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;
5、格式化服务器返回的JSON数据
- 在线格式化:http://tool.oschina.net/codeformat/json
- 将服务器返回的字典或者数组写成plist文件
6、JSON解析小案例
- 解析来自服务器的JSON
解析JSON.png
#import "ViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import <MediaPlayer/MPMoviePlayerViewController.h>
#import "JPVideo.h"
#import <MJExtension/MJExtension.h>
@interface ViewController ()
@property (nonatomic, strong) NSArray *videos; /**< 视屏信息 */
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 只需要在字典转模型之前, 告诉框架要将模型中的哪个属性和字典中的哪个KEY对应
[JPVideo setupReplacedKeyFromPropertyName:^NSDictionary *{
return @{@"ID":@"id"};
}];
self.tableView.rowHeight = 150;
// Do any additional setup after loading the view, typically from a nib.
NSURL *url = [NSURL URLWithString:@"/video?type=JSON"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
// 解析来自服务器的data的josn数据 - > OC字典
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
// self.videos = dict[@"videos"];
// 字典转模型
/*
NSMutableArray *models = [NSMutableArray array];
for (NSDictionary *videoDict in dict[@"videos"]) {
JPVideo *video = [JPVideo videoWithDict:videoDict];
[models addObject:video];
}
self.videos = [models copy];
*/
/* 使用MJExtension的优点:
1.没有任何依赖关系
2.模型中的属性, 不用和字典中的key一一对应
*/
self.videos = [JPVideo objectArrayWithKeyValuesArray:dict[@"videos"]];
// 注意: 拿到数据之后一定要刷新表格
[self.tableView reloadData];
}];
}
#pragma mark - datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.videos.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 1.创建cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
// 2.取出对应行的字典
JPVideo *video = self.videos[indexPath.row];
// 2.1设置数据
cell.textLabel.text = video.name;
cell.detailTextLabel.text = [NSString stringWithFormat:@"时长:%@", video.length];
NSString *urlStr = [NSString stringWithFormat:@"http://120.25.226.186:32812/%@", video.image];
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:nil];
// 3.返回cell
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// 1.取出选中行对应的字典
JPVideo *video = self.videos[indexPath.row];
// 2.根据字典中的URL属性拼接视屏的地址
NSString *urlStr = [NSString stringWithFormat:@"/%@", video.url];
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlStr];
// 3.播放视屏
MPMoviePlayerViewController *vc = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
// 4.显示控制器
[self presentViewController:vc animated:YES completion:nil];
}
@end