標籤:
一、什麼是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
IOS開發網路篇-JSON檔案的解析