iOS-----JSON解析,iosjson

來源:互聯網
上載者:User

iOS-----JSON解析,iosjson
JSON解析

JSON是一種廣泛使用的資料交換格式,JSON同樣具有跨平台、跨語言的優勢,而且使用JSON作為資料交換格式時資料轉送量更小。

JSON的基本知識

JSON的全稱是JavaScript Object Notation,即JavaScript 對象符號,它是一種輕量級的資料交換格式.JSON資料格式既適合人進行讀/寫,也適合電腦本身解析和產生。

JSON主要有如下兩種資料結構

由key-value對組成的資料結構,在不同的語言中有不同的實現。例如,在JavaScript中是一個對象,在Objective-C中是一種NSDictionary對象,在C語言中則是一個struct,在其他語言中可能有record、dictionary、hash table等實現

有序集合,在不同語言中可能有NSArray、vector、數組和序列等實現。

在JavaScript中主要有兩種JSON文法,其中一種用於建立對象,另一種用於建立數組。

 

使用JSON文法建立對象

   JSON建立對象時,總是{開始,以}結束,對象的每個屬性名稱和屬性值之間以英文冒號(:)隔開,多個屬性定義之間以英文逗號(,)隔開.文法格式如下:

 1 object  = 2  3 { 4  5      propertyName1 : propertyValue1, 6  7       propertyName2 : propertyValue2, 8  9       …10 11 }

 

使用JSON文法建立數組

  使用JSON文法建立數組總是以英文方括弧( [ )開始,然後依次放入數組元素,元素與元素之間以英文逗號( , )隔開,最後一個數組元素後面不需要英文逗號,但以英文反方括弧 ( ] ).使用JSON建立數組的文法格式如下:

arr = [value1 , value2,…];

 

對於Objective-C的JSON工具而言,同樣提供類似的兩個功能

將Objective-C對象轉換成JSON格式的字串

將JSON格式的字串恢複成Objective-C對象

 

使用NSJSONSerialization處理JSON資料

NSJSONSerialization類提供了如下類方法來支援JSON解析或產生

 

NSJSONSerialization只能將滿足如下條件的對象轉換為JSON資料

 

使用SBJson解析JSON資料

     SBJson同樣可以完成雙向轉換,它最主要的連個工具類就是SBJsonParser和SBJsonWriter,

其中SBJsonParser負責把NSData或NSString形式的JSON資料轉換為Objective-C對象;

而SBJsonWriter則負責把Objective-C對象轉換為NSData或NSString形式的JSON資料.

使用JSONKit解析JSON資料
  1 ViewController.m  2   3 #import “ViewController.h”  4   5 #import “SBJson.h”  6   7 #import “JSONKit.h”  8   9 @implementation ViewController 10  11 NSArray* books; 12  13 NSArray* parseResult; 14  15 NSString* tableTitle; 16  17 - (void)viewDidLoad 18  19 { 20  21    [super viewDidLoad]; 22  23   // 定義一個Objective-C的NSArray資料,該樣本會使用3種方式將該對象轉換為JSON資料 24  25  books = [NSArray arrayWithObjects: 26  27 [NSDictionary  dictionaryWithObjectsAndKeys@”紅樓夢”, @”title”, 28  29 @”曹雪芹 編著” , @”author”, 30  31 @”書寫了清朝曆史豪門的縮影”, @”remark” , nil ] , 32  33 [NSDictionary  dictionaryWithObjectsAndKeys@”三國演義”, @”title”, 34  35 @”羅貫中 編著” , @”author”, 36  37 @”天下分久必合合久必分”, @”remark” , nil ] , 38  39 [NSDictionary  dictionaryWithObjectsAndKeys@”西遊記”, @”title”, 40  41 @”吳承恩 編著” , @”author”, 42  43 @”去西天取經”, @”remark” , nil ] , 44  45 [NSDictionary  dictionaryWithObjectsAndKeys@”水滸傳”, @”title”, 46  47 @”施耐庵 編著” , @”author”, 48  49 @”草根”, @”remark” , nil ] 50  51 ,nil]; 52  53 self.tableView.dataSource = self; 54  55 } 56  57 - (IBAction)JSONSerializationParser:(id)sender 58  59 { 60  61    // 擷取JSON檔案所在的路徑 62  63   NSString* jsonPath = [[NSBundle mainBundle] pathForResource:@”books” 64  65 ofType@”json”]; 66  67 // 讀取jsonPath對應檔案的資料 68  69 NSData* data = [NSData dataWithContentsOfFile:jsonPath]; 70  71 // 解析JSON資料,返回Objective-C對象 72  73 parseResult = [NSJSONSerialization JSONObjectWithData:data 74  75 options:0 error:nil]; 76  77 tableTitle = @”使用JSONSerializationParse解析”; 78  79 // 讓tableView重新載入資料 80  81 [self.tableView reloadData]; 82  83 } 84  85 - (IBAction)SBParser:(id)sender 86  87 { 88  89    // 擷取JSON檔案所在的路徑 90  91   NSString* jsonPath = [[NSBundle mainBundle] pathForResource:@”books” 92  93 ofType:@”json”]; 94  95 // 讀取jsonPath對應檔案的資料 96  97 NSData* data = [NSData dataWithContentsOfFile:jsonPath]; 98  99 // 建立SBJsonParser對象100 101 SBJsonParser* jsonParser = [[SBJsonParser alloc] init];102 103 parserResult = [jsonParser objectWithData:data];104 105 tableTitle = @”使用SBJson解析”;106 107 // 讓tableView重新載入資料108 109 [self.tableView reloadData];110 111 }112 113 - (IBAction)JSONKitParse:(id)sender114 115 {116 117    // 擷取JSON檔案所在的路徑118 119   NSString* jsonPath = [[NSBundle mainBundle] pathForResource:@”books”120 121 ofType:@”json”];122 123 //  讀取jsonPath對應檔案的資料124 125 NSData* data = [NSData dataWithContentsOfFile:jsonPath];126 127 //  調用JSONKit為NSData擴充的objectFromJSONData方法解析JSON資料128 129 parseResult = [data objectFromJSONData];130 131 tableTitle = @”使用JSONKit解析”;132 133  //  讓tableView重新載入資料134 135 [self.tableView reloadData];136 137 }138 139 - (IBAction)JSONSerializtionGenerate:(id)sender140 141 {142 143    // 調用NSJSONSerialization的類方法將Objective-C對象轉換為JSON資料144 145    NSData* data = [NSJSONSerialization dataWithJSONObject:books146 147 options:0  error: nil];148 149 //  將NSData格式的JSON資料轉換為字串150 151 NSString* json = [[NSString alloc] initWithData:data152 153 encoding:NSUTF8StringEncoding];154 155 NSLog(@”NSJSONSerialization 轉換得到的字串為:%@”,  json);156 157 }158 159 - (IBAction)SBGenerate:(id)sender160 161 {162 163    // 建立SBJsonWriter對象164 165   SBJsonWriter* jsonWriter = [[SBJsonWriter alloc] init];166 167   // 調用SBJsonWriter對象的方法將Objective-C對象轉換為JSON字串168 169   NSLog(@”SBJson 轉換得到字串為:  %@”, [jsonWriter stringWithObject: books]);170 171 }172 173 - (IBAction)JSONKitGenerate:(id)sender174 175 {176 177   // 調用JSONKit為NSArray對象擴充的JSONString方法將Objective-C對象轉換為JSON字串178 179   NSLog(@”JSONKit 轉換得到字串為:  %@”, [books JSONString]);180 181 }182 183 - (NSString*)tableView:(UITableView *)tableView184 185 titleForHeaderInSection:(NSInteger)section186 187 {188 189   return  tableTitle;190 191 }192 193 - (NSInteger)tableView:(UITableView*)tableView194 195   numberOfRowsInSection: (NSInteger)section196 197 {198 199    // parseResult中包含多少個對象,該表格就顯示多少行200 201    retrun [parseResult  count];202 203 }204 205 - (UITableViewCell*)tableView:(UITableView*)tableView206 207  cellForRowAtIndexPath:(NSIndexPath*)indexPath208 209 {210 211    // 根據動態儲存格原型的ID來擷取可重用儲存格212 213   UITableViewCell* cell = [tableView  dequeueReusableCellWithIdentifier:@”bookCell”214 215 forIndexPath: indexPath];216 217 // 擷取當前行號在parserResult中對應的資料218 219 NSDictionary* book = [parseResult  objectAtIndex: indexPath.row];220 221 // 擷取儲存格中的3個控制項,並為3個控制項設定顯示文本222 223 UILabel* titleLabel = (UILabel*)[cell  viewWithTag:1];224 225 titleLabel.text = [book objectForKey:@”title”];226 227 UILabel* authorLabel = (UILabel* )[cell viewWithTag:2];228 229 authorLabel.text = [book objectForKey:@”author”];230 231 UILabel* remarkLabel = (UILabel* )[cell viewWithTag:2];232 233 authorLabel.text = [book objectForKey:@”remark”];234 235 }236 237 @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.