iOS開(kāi)發(fā)使用JSON解析網(wǎng)絡(luò)數(shù)據(jù)
前言:對(duì)服務(wù)器請(qǐng)求之后,返回給客戶(hù)端的數(shù)據(jù),一般都是JSON格式或者XML格式(文件下載除外)
本篇隨便先講解JSON解析。
正文:
關(guān)于JSON:
JSON是一種輕量級(jí)的數(shù)據(jù)格式,一般用于數(shù)據(jù)交互JSON的格式很像Objective-C中的字典和數(shù)組:{"name":"jack","age":10}
補(bǔ)充:
標(biāo)準(zhǔn)的JSON格式的注意點(diǎn):key必須用雙引號(hào)。(但是在Java中是單引號(hào))
JSON-OC的轉(zhuǎn)換對(duì)照表
其中:null--返回OC里的NSNull類(lèi)型
使用:
在JSON解析方案有很多種,但是(蘋(píng)果原生的)NSJSONSerialization性能最好
反序列化(JSON --> OC對(duì)象),下面示例解析成字典對(duì)象
序列化(OC對(duì)象 --> JSON),注意字典的值不能傳nil,但是可以傳[NSNull null]
并不是所有的類(lèi)型都是可以轉(zhuǎn)為JSON的
以下是蘋(píng)果官方規(guī)定:
我們?cè)賮?lái)看個(gè)實(shí)例:
#import "MainViewController.h" #import "Video.h" #define kBaseURL @"http://192.168.3.252/~apple" @interface MainViewController () @property (strong, nonatomic) NSArray *dataList; @property (weak, nonatomic) UITableView *tableView; @end @implementation MainViewController class="p1"> "412158" snippet_file_name="blog_20140630_1_3481337" name="code" class="objc"> #pragma mark 實(shí)例化視圖 - (void)loadView { self.view = [[UIView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame]; //1 tableview CGRect frame = self.view.bounds; UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height - 44) style:UITableViewStylePlain]; //1)數(shù)據(jù)源 [tableView setDataSource:self]; //2)代理 [tableView setDelegate:self]; //)設(shè)置表格高度 [tableView setRowHeight:80]; [self.view addSubview:tableView]; self.tableView = tableView; //toolBar UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, tableView.bounds.size.height, 320, 44)]; [self.view addSubview:toolBar]; //添加toolbar按鈕 UIBarButtonItem *item1 = [[UIBarButtonItem alloc]initWithTitle:@"load json" style:UIBarButtonItemStyleDone target:self action:@selector(loadJson)]; UIBarButtonItem *item2 = [[UIBarButtonItem alloc]initWithTitle:@"load xml" style:UIBarButtonItemStyleDone target:self action:@selector(loadXML)]; UIBarButtonItem *item3 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; [toolBar setItems:@[item3, item1, item3, item2, item3]]; } #pragma mark -uitableview數(shù)據(jù)源方法 對(duì)于uitableview下面這兩個(gè)方法是必須實(shí)現(xiàn)的。 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.dataList.count; } //每填充一行都調(diào)用一次這個(gè)方法。知道界面上的所有行都填充完畢。, - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //使用可充用標(biāo)示符查詢(xún)可重用單元格 static NSString *ID = @"MyCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; if (cell == nil) { cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID]; } //設(shè)置單元格內(nèi)容 Video *v = self.dataList[indexPath.row]; cell.textLabel.text = v.name; cell.detailTextLabel.text = v.teacher; //加載圖片 //1)同步加載網(wǎng)絡(luò)圖片,同步方法以為這這些指令在完成之前,后續(xù)指令都無(wú)法執(zhí)行。 //注意:在開(kāi)發(fā)網(wǎng)絡(luò)應(yīng)用時(shí),不要使用同步方法加載圖片,否則會(huì)嚴(yán)重影響用戶(hù)體驗(yàn) // NSString *imagePath = [NSString stringWithFormat:@"%@%@", kBaseURL, v.imageURL]; // NSURL *imageUrl = [NSURL URLWithString:imagePath]; // NSData *imageData = [NSData dataWithContentsOfURL:imageUrl]; // UIImage *image = [UIImage imageWithData:imageData]; // // //2)異步加載網(wǎng)絡(luò)圖片 // //網(wǎng)絡(luò)連接本身就有異步命令 sendAsync // [cell.imageView setImage:image]; //如果緩存圖像不存在 if (v.cacheImage == nil) { //使用默認(rèn)圖像占位,即能夠保證有圖像,又能夠保證有地方。 UIImage *image = [UIImage imageNamed:@"user_default.png"]; [cell.imageView setImage:image]; //使用默認(rèn)圖像占位 //開(kāi)啟異步連接,加載圖像,因?yàn)榧虞d完成之后,需要刷新對(duì)應(yīng)的表格航 [self loadImageAsyncWithIndexPath:indexPath]; }else { [cell.imageView setImage:v.cacheImage]; } //[self loadImageAsyncWithUrl:imageUrl imageView:cell.imageView]; return cell; } #pragma mark 異步加載網(wǎng)絡(luò)圖片 //由于uitableview是可重用的,為了避免用戶(hù)快速頻繁刷新表格,造成數(shù)據(jù)沖突,不能直接將uiimageview傳入異步方法 //正確的解決方法是:將表格行的indexpath傳入異步方法,加載完成圖像以后,直接刷新指定的行。 - (void)loadImageAsyncWithIndexPath:(NSIndexPath *)indexPath { Video *v = self.dataList[indexPath.row]; //取出當(dāng)前要填充的行 NSString *imagePath = [NSString stringWithFormat:@"%@%@", kBaseURL, v.imageURL]; NSURL *imageUrl = [NSURL URLWithString:imagePath]; //NSLog(@"%@ %@", url, imageView); //1 request NSURLRequest *request = [NSURLRequest requestWithURL:imageUrl]; //2 connection sendasync異步請(qǐng)求 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { //UIImage *image = [UIImage imageWithData:data]; //[imageView setImage:image]; //將網(wǎng)絡(luò)數(shù)據(jù)保存至緩存圖像。 v.cacheImage = [UIImage imageWithData:data]; //刷新表格 [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft]; }]; } #pragma mark 處理json數(shù)據(jù) - (void)handlerJSONData:(NSData *)data { //json文件中的[]表示一個(gè)數(shù)據(jù)。 //反序列化json數(shù)據(jù) //第二個(gè)參數(shù)是解析方式,一般用NSJSONReadingAllowFragments NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; NSLog(@"%@", array); //json解析以后是nsarray格式的數(shù)據(jù)。 //提示:如果開(kāi)發(fā)網(wǎng)絡(luò)應(yīng)用,可以將反序列化出來(lái)的對(duì)象,保存至沙箱,以便后續(xù)開(kāi)發(fā)使用。 NSArray *docs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *path = [docs[0]stringByAppendingPathComponent:@"json.plist"]; [array writeToFile:path atomically:YES]; //把a(bǔ)rray里面的數(shù)據(jù)寫(xiě)入沙箱中的jspn.plist中。 //給數(shù)據(jù)列表賦值 NSMutableArray *arrayM = [NSMutableArray array]; for (NSDictionary *dict in array) { Video *video = [[Video alloc]init]; //給video賦值 [video setValuesForKeysWithDictionary:dict]; [arrayM addObject:video]; } self.dataList = arrayM; //刷新表格 [self.tableView reloadData]; NSLog(@"%@", arrayM); //這句話(huà)將調(diào)用video里面的description和nsarray+log里面的descriptionWithLocale } #pragma mark 加載json - (void)loadJson { NSLog(@"load json"); //從web服務(wù)器加載數(shù)據(jù) NSString *str = @"http://www.baidu.com?format=json"; //這里是亂寫(xiě)的 //提示:NSData本身具有同步方法,但是在實(shí)際開(kāi)發(fā)中,不要使用次方法 //在使用NSData的同步方法時(shí),無(wú)法指定超時(shí)時(shí)間,如果服務(wù)器連接不正常,會(huì)影響用戶(hù)體驗(yàn)。 //NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]]; //簡(jiǎn)歷NSURL NSURL *url = [NSURL URLWithString:str]; //建立NSURLRequest NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2.0f]; //建立NSURLConnect的同步方法加載數(shù)據(jù) NSURLResponse *response = nil; NSError *error = nil; //同步加載數(shù)據(jù) NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; //錯(cuò)誤處理 if (data != nil) { //下面這兩句話(huà)本身沒(méi)有什么意義,僅用于跟蹤調(diào)試。 NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", result); //在處理網(wǎng)絡(luò)數(shù)據(jù)的時(shí)候,不要將NSData轉(zhuǎn)換成nsstring。 [self handlerJSONData:data]; }else if (data == nil && error == nil){ NSLog(@"空數(shù)據(jù)"); }else { NSLog(@"%@", error.localizedDescription); } } #pragma mark 加載xml - (void)loadXML { NSLog(@"load xml"); } //- (void)viewDidLoad //{ // [super viewDidLoad]; //} @end
- iOS中json解析出現(xiàn)的null,nil,NSNumber的解決辦法
- IOS中Json解析實(shí)例方法詳解(四種方法)
- iOS json解析出錯(cuò)的幾種情況總結(jié)
- 詳解iOS開(kāi)發(fā)中解析JSON中的boolean類(lèi)型的數(shù)據(jù)遇到的問(wèn)題
- IOS 簡(jiǎn)單的本地json格式文件解析的實(shí)例詳解
- IOS json 解析遇到錯(cuò)誤問(wèn)題解決辦法
- IOS開(kāi)發(fā)之JSON轉(zhuǎn)PLIST實(shí)例詳解
- iOS Swift讀取本地json文件報(bào)錯(cuò)的解決方法
- 談?wù)刬OS開(kāi)發(fā)之JSON格式數(shù)據(jù)的生成與解析
- iOS讀寫(xiě)json文件的方法示例
相關(guān)文章
iOS購(gòu)物分類(lèi)模塊的實(shí)現(xiàn)方案
這篇文章主要為大家詳細(xì)介紹了iOS購(gòu)物分類(lèi)模塊的實(shí)現(xiàn)方案,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-02-02iOS開(kāi)發(fā) widget構(gòu)建詳解及實(shí)現(xiàn)代碼
這篇文章主要介紹了iOS開(kāi)發(fā) widget構(gòu)建詳解的相關(guān)資料,并附實(shí)例代碼,需要的朋友可以參考下2016-11-11ios uicollectionview實(shí)現(xiàn)橫向滾動(dòng)
這篇文章主要為大家詳細(xì)介紹了ios uicollectionview實(shí)現(xiàn)橫向滾動(dòng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-03-03iOS中的AutoLayout使用實(shí)踐總結(jié)
在對(duì)界面進(jìn)行布局的時(shí)候,我們經(jīng)常使用AutoLayout對(duì)界面進(jìn)行布局適配。下面這篇文章主要給大家介紹了iOS中AutoLayout使用實(shí)踐的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面來(lái)一起看看吧。2017-12-12iOS使用WebView生成長(zhǎng)截圖的第3種解決方案
這篇文章主要給大家介紹了關(guān)于iOS使用WebView生成長(zhǎng)截圖的第3種解決方案,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-09-09簡(jiǎn)介iOS開(kāi)發(fā)中應(yīng)用SQLite的模糊查詢(xún)和常用函數(shù)
這篇文章主要介紹了iOS開(kāi)發(fā)中應(yīng)用SQLite的模糊查詢(xún)和常用函數(shù),SQLite是一個(gè)可作嵌入式的數(shù)據(jù)庫(kù)非常適合小型應(yīng)用使用,需要的朋友可以參考下2015-12-12