JSON解析 實現界面 數據分離.

JSONjavascript

做爲一種輕量級的數據交換格式,正在逐步取代XML,成爲網絡數據的通用格式java

基於JavaScript的一個子集json

易讀性略差,編碼手寫難度大,數據量小數組

JSON格式取代了XML給網絡傳輸帶來了很大的便利,可是卻沒有了XML的一目瞭然,尤爲是JSON數據很長的時候,咱們會陷入繁瑣複雜的數據節點查找中服務器

JSON格式說明網絡

對象異步

{}async

格式 {key : value, key : value,...} 的鍵值對的結構ide

能夠反序列化爲OC中的NSDictionary性能

數組

[]

格式 ["java","javascript","vb",...]

能夠反序列化爲OC中的NSArray

提示

JSON的數據格式與OC中的快速包裝方法很是相似

JSON的數據格式一樣支持嵌套

 

 

解析服務器端返回JSON數據

 

從iOS 5開始,使用NSJSONSerialization對JSON解析

 

其餘常見的三種JSON解析第三方庫:

SBJson 由於API簡單易用,可能還會有一些應用中留存

JSONKit JSONKit的開發者稱:JSONKit的性能優於蘋果

TouchJson

 

 

JSON的序列化和反序列化

反序列化

[NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];

 

序列化

[NSJSONSerialization dataWithJSONObject:array options:0 error:NULL];

 

NSJSONReadingOptions

NSJSONReadingMutableContainers = 1,    根節點可變

NSJSONReadingMutableLeaves = 2,          節點可變

NSJSONReadingAllowFragments = 4,         根節點能夠不是NSDictionary或者NSArray

 

 

 

 

//代碼解析步驟

#import <Foundation/Foundation.h>

 

@interface Video : NSObject

 

@property (nonatomic, copy) NSNumber *videoId;

@property (nonatomic, copy) NSString *name;

@property (nonatomic, copy) NSNumber *length;

@property (nonatomic, copy) NSString *videoURL;

@property (nonatomic, copy) NSString *imageURL;

@property (nonatomic, copy) NSString *desc;

 

- (instancetype)initWithDict:(NSDictionary *)dict;

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

 

@end

 

 

#import "Video.h"

@implementation Video

 

- (instancetype)initWithDict:(NSDictionary *)dict

{

    self = [super init];

    if (self) {

        [self setValuesForKeysWithDictionary:dict];

    }

    return self;

}

 

+ (instancetype)videoWithDict:(NSDictionary *)dict

{

    return [[self alloc] initWithDict:dict];

}

 

 

 

@end

 

 

 

//解析步驟

#import "PLMJSONViewController.h"

#import "Video.h"

 

@interface PLMJSONViewController ()

 

@end

 

@implementation PLMJSONViewController

 

/** 重寫父類的加載數據方法 */

- (void)loadData

{

    NSLog(@"%s", __func__);

    

    // 1. url

    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/videos.json"];

    

    // 2. request

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    

    // 3. 發送異步請求

    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        

        // data是一個json數據

        // 對data進行反序列化,解析(不少時候咱們解析出來的是字典)

        NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];

        

        // 創建視頻的數組

        NSMutableArray *arrayM = [NSMutableArray array];

        

        for (NSDictionary *dict in array) {

            [arrayM addObject:[Video videoWithDict:dict]];

        }

        

        // 刷新數據,更新UI

        dispatch_async(dispatch_get_main_queue(), ^{

            self.dataList = arrayM;

        });

    }];

}

 

@end

 

#import <UIKit/UIKit.h>

 

@interface PLMViewController : UITableViewController

 

@property (nonatomic, strong) NSArray *dataList;

 

/** 加載網絡數據 */

- (void)loadData;

 

@end

 

#import "PLMViewController.h"

#import "Video.h"

 

@interface PLMViewController ()

 

@end

 

@implementation PLMViewController

 

/** 設置表格的數組數據 */

- (void)setDataList:(NSArray *)dataList

{

    _dataList = dataList;

    

    // 表格的數據源,綁定在dataList,當從新設置了dataList的內容,須要刷新表格

    [self.tableView reloadData];

    

    // 中止刷新控件

    [self.refreshControl endRefreshing];

}

 

- (void)viewDidLoad

{

    [super viewDidLoad];

    

    // 加載網絡數據

    [self loadData];

}

 

- (IBAction)refresh

{

    [self loadData];

}

 

- (void)loadData

{

    // 此方法的具體實如今子類中

}

 

#pragma mark - 表格的數據源方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return self.dataList.count;

}

 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *ID = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

    

    Video *v = self.dataList[indexPath.row];

    cell.textLabel.text = v.name;

    

    return cell;

}

 

@end

相關文章
相關標籤/搜索