iOS開發 - JSON解析

來源:互聯網
上載者:User

iOS開發 - JSON解析
JSON解析

什麼是JSON
JSON是一種輕量級的資料格式,一般用於資料互動
伺服器返回給用戶端的資料,一般都是JSON格式或者XML格式(檔案下載除外)

JSON的格式很像OC中的字典和數組

{"name" : "jack", "age" : 10}{"names" : ["jack", "rose", "jim"]}

標準JSON格式的注意點:key必須用雙引號

要想從JSON中挖掘出具體資料,得對JSON進行解析
JSON 轉換為 OC資料類型

JSON – OC 轉換對照表
JSON OC
大括弧 { } NSDictionary
中括弧 [ ] NSArray
雙引號 ” “ NSString
數字 10、10.8 NSNumber
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;
解析來自伺服器的JSON

JSON解析執行個體
@interface ViewController ()@property (weak, nonatomic) IBOutlet UITextField *username;@property (weak, nonatomic) IBOutlet UITextField *pwd;- (IBAction)login;@end@implementation ViewController- (void)viewDidLoad{    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.}- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{    [self.view endEditing:YES];}- (IBAction)login {    // 1.使用者名稱    NSString *usernameText = self.username.text;    if (usernameText.length == 0) {        [MBProgressHUD showError:@"請輸入使用者名稱"];        return;    }    // 2.密碼    NSString *pwdText = self.pwd.text;    if (pwdText.length == 0) {        [MBProgressHUD showError:@"請輸入密碼"];        return;    }    // 3.發送使用者名稱和密碼給伺服器(走HTTP協議)    // 建立一個URL : 請求路徑    NSString *urlStr = [NSString stringWithFormat:@"http://localhost:8080/Server/login?username=%@&pwd=%@",usernameText, pwdText];    NSURL *url = [NSURL URLWithString:urlStr];    // 建立一個請求    NSURLRequest *request = [NSURLRequest requestWithURL:url];//    NSLog(@"begin---");    // 發送一個同步請求(在主線程發送請求)    // queue :存放completionHandler這個任務    NSOperationQueue *queue = [NSOperationQueue mainQueue];    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:     ^(NSURLResponse *response, NSData *data, NSError *connectionError) {        // 這個block會在請求完畢的時候自動調用        if (connectionError || data == nil) {            [MBProgressHUD showError:@"請求失敗"];            return;        }        // 解析伺服器返回的JSON資料        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];        NSString *error = dict[@"error"];        if (error) {            // {"error":"使用者名稱不存在"}            // {"error":"密碼不正確"}            [MBProgressHUD showError:error];        } else {            // {"success":"登入成功"}            NSString *success = dict[@"success"];            [MBProgressHUD showSuccess:success];        }     }];//    NSLog(@"end---");}@end
視屏JSON資料解析執行個體

模型類

#import @interface Video : NSObject/** *  ID */@property (nonatomic, assign) int id;/** *  時間長度 */@property (nonatomic, assign) int length;/** *  圖片(視頻) */@property (nonatomic, copy) NSString *image;/** *  視頻名字 */@property (nonatomic, copy) NSString *name;/** *  視頻的播放路徑 */@property (nonatomic, copy) NSString *url;+ (instancetype)videoWithDict:(NSDictionary *)dict;@end
#import "Video.h"@implementation Video+ (instancetype)videoWithDict:(NSDictionary *)dict{    Video *video = [[self alloc] init];    [video setValuesForKeysWithDictionary:dict];    return video;}@end
#import #define Url(path) [NSURL URLWithString:[NSString stringWithFormat:@"http://localhost:8080/Server/%@", path]]@interface VideosViewController ()@property (nonatomic, strong) NSMutableArray *videos;@end@implementation VideosViewController- (NSMutableArray *)videos{    if (!_videos) {        self.videos = [[NSMutableArray alloc] init];    }    return _videos;}- (void)viewDidLoad{    [super viewDidLoad];    /**     載入伺服器最新的視頻資訊     */    // 1.建立URL    NSURL *url = Url(@"video");    // 2.建立請求    NSURLRequest *request = [NSURLRequest requestWithURL:url];    // 3.發送請求    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {        if (connectionError || data == nil) {            [MBProgressHUD showError:@"網路繁忙,請稍後再試!"];            return;        }        // 解析JSON資料        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];        NSArray *videoArray = dict[@"videos"];        for (NSDictionary *videoDict in videoArray) {            HMVideo *video = [HMVideo videoWithDict:videoDict];            [self.videos addObject:video];        }        // 重新整理表格        [self.tableView reloadData];    }];}#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 *ID = @"video";    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];    if (!cell) {        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];    }    HMVideo *video = self.videos[indexPath.row];    cell.textLabel.text = video.name;    cell.detailTextLabel.text = [NSString stringWithFormat:@"時間長度 : %d 分鐘", video.length];    // 顯示視頻    NSURL *url = HMUrl(video.image);    [cell.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placehoder"]];    return cell;}#pragma mark - 代理方法- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{    // 1.取出對應的視頻模型    HMVideo *video = self.videos[indexPath.row];    // 2.建立系統內建的視頻播放控制器    NSURL *url = Url(video.url);    MPMoviePlayerViewController *playerVc = [[MPMoviePlayerViewController alloc] initWithContentURL:url];    // 3.顯示播放器    [self presentViewController:playerVc animated:YES completion:nil];}@end

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.