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

iOS开发网络篇-JSON文件的解析

2015-08-17 22:11 686 查看

一、什么是JSON数据

  1.JSON的简单介绍 

  JSON:是一种轻量级的传输数据的格式,用于数据的交互    

  JSON是javascript语言的一个子集.javascript是个脚本语言(不需要编译),用来给HTML增加动态功能.

 javascript和java没有半毛钱的关系!

服务器返回给客户端的数据,一般都是JSON格式或者XML格式(文件下载除外).

2.JSON的语法规则      

<1> 数据以键值的方式保存;

键(key)必须用双引号("key"),与键值之间以':'分隔; {"name":"小明"}

<2> 数据和数据之间以逗号(,)分隔. {"name":"小明","age":13}

<3> {}表示对象. "person":{"name":"小明","age":13}

<4> []表示数组. "persons":[

{"name":"小明","age":13},

{"name":"小红","age":14},

{"name":"小花","age":15}

]

3.JSON与OC转换对照  

  大括号 {} == NSDictionary;

中括号 [] == NSArray;

双引号" " == NSString;

数字13,13.5 == NSNumber;

注意:数字推荐使用NSNumber来接收,为了更好针对null赋值

二、JSON的解析(反序列化)

    反序列化: 将从服务器接收到的JSON数据(二进制数据)转换成OC数据类型(NSArray,NSDictionary等.)的过程.

目的: JSON数据 --> OC对象; 得到数据字典或者数据数组

好处: 简化程序的开发,方便后续的字典转模型.

  1.JSON的数据解析的方式

  在iOS中,常见的JSON数据解析方案有4种:

第三方框架:JSONKit, SBJson, TouchJson.性能从左到右,依次变差.(iOS 5(2011年)以前)

苹果原生(自带):NSJSONSerialization (性能是最好的.iOS5以后推出).  

例程演示:

   从本地搭建的服务器中读取JSON文件,并且显示出来到一个tableView上面

  本地服务器资源: 


 

JSON文件截图

 


效果图:

      

 

代码实现:

  

//
//  GXVideo.h
//  03-JSON的数据解析
//
//  Created by gxiangzi on 15/8/17.
//  Copyright (c) 2015年 hqu. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface GXVideo : NSObject

@property (copy, nonatomic) NSString* length;

@property (copy, nonatomic) NSString* url;

@property (copy, nonatomic) NSString* image;

@property (copy, nonatomic) NSString* ID;

@property (copy, nonatomic) NSString* name;

+ (instancetype)videoWithDict:(NSDictionary *)dict;

@end


 

//
//  GXVideo.m
//  03-JSON的数据解析
//
//  Created by gxiangzi on 15/8/17.
//  Copyright (c) 2015年 hqu. All rights reserved.
//

#import "GXVideo.h"

@implementation GXVideo

+ (instancetype)videoWithDict:(NSDictionary *)dict
{
GXVideo *video = [[self alloc] init];
[video setValuesForKeysWithDictionary:dict];
return video;
}

@end


//
//  GXViewController.h
//  03-JSON的数据解析
//
//  Created by gxiangzi on 15/8/17.
//  Copyright (c) 2015年 hqu. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface GXViewController : UITableViewController

@end


//
//  GXViewController.m
//  03-JSON的数据解析
//
//  Created by gxiangzi on 15/8/17.
//  Copyright (c) 2015年 hqu. All rights reserved.
//

#import "GXViewController.h"
#import "GXVideo.h"
#import "UIImageView+WebCache.h"

#import <MediaPlayer/MediaPlayer.h>

@interface GXViewController ()

@property (nonatomic, strong) NSMutableArray* videos;

@end

@implementation GXViewController

#pragma mark -懒加载
- (NSMutableArray*)videos
{
if (!_videos) {
_videos = [NSMutableArray array];
}
return _videos;
}

- (void)viewDidLoad
{
[super viewDidLoad];

// 从网络解析数据
NSString* urlString = @"http://localhost/resources/vedios.json";
NSURL* url = [NSURL URLWithString:urlString];

// 创建一个网络请求
NSURLRequest* request = [NSURLRequest requestWithURL:url];

__weak typeof(self) wself = self;

// 发送一个网络请求
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse* response, NSData* data, NSError* connectionError) {
// 链接成功之后的操作返回Data

// 数据转换成JSON
NSArray* arrayVideo = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:NULL];

[arrayVideo enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL* stop) {
NSDictionary* dict = obj;
GXVideo* video = [GXVideo videoWithDict:dict];

[wself.videos addObject:video];

}];

[wself.tableView reloadData];

}];
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
return self.videos.count;
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
static NSString* resuedId = @"cell";
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:resuedId];

if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:resuedId];
}

GXVideo* video = self.videos[indexPath.row];

cell.textLabel.text = video.name;

NSString* timeDetail = [NSString stringWithFormat:@"时长: %@ 分钟", video.length];

cell.detailTextLabel.text = timeDetail;

// 利用三方框架SDWebImage
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:video.image] placeholderImage:[UIImage imageNamed:@"placeholder-1"]];

return cell;
}

#pragma mark - 播放视频
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
GXVideo* video = self.videos[indexPath.row];

NSURL* url = [NSURL URLWithString:video.url];

// 创建一个播放器
MPMoviePlayerViewController* media = [[MPMoviePlayerViewController alloc] initWithContentURL:url];

[self presentMoviePlayerViewControllerAnimated:media];
}

@end


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: