iOS JSON 資料解析,iosjson資料解析

來源:互聯網
上載者:User

iOS JSON 資料解析,iosjson資料解析

JSON 是比較常用的資料格式,相比 XML 層次更清晰,這裡介紹兩種解析 JSON 的方式:NSJSONSerialization 和 JSONKit

NSJSONSerialization 是 iOS 5 以後推出的,比較好用的 JSON 解析包.

JSON 資料格式由對應的 '[',']' 和 '{','}',前者表示數組,後者表示字典.

NSJSONSerialization 解析過程:

1.擷取檔案路徑

2.擷取檔案內容

3.解析

簡單小例子:

 1 - (IBAction)parserJSON:(id)sender { 2      3     //擷取檔案路徑 4      5     NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"Student" ofType:@"json"]; 6     NSError *error = nil; 7     NSData *jsonData = [NSData dataWithContentsOfFile:jsonPath]; 8     NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error]; 9     if (error == nil) {10         NSLog(@"%@",array);11     }else {12         NSLog(@"%@",error);13     }14     15     //資料封裝16     17     NSMutableArray *arr = [NSMutableArray array];18     19     for (NSDictionary *dic in array) {20         Student *stu = [[Student alloc]initWithDictionary:dic];21         [arr addObject:stu];22     }23     24     for (Student *stu in arr) {25         NSLog(@"%@",stu);26     }27 }

 

JSONKit 解析:(代碼)

 1 - (IBAction)parserJSONWithJESONKIT:(id)sender { 2      3     //擷取檔案路徑 4      5     NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"Student" ofType:@"json"]; 6     NSError *error = nil; 7     NSString *JSONStr = [[NSString alloc]initWithContentsOfFile:jsonPath encoding:NSUTF8StringEncoding error:&error]; 8     NSLog(@"%@",JSONStr); 9     //讓jesonKIT 解析 JSON 資料10     NSMutableArray *array = [JSONStr objectFromJSONString];11     NSLog(@"%ld",array.count);12     //資料封裝13     NSMutableArray *arr = [NSMutableArray array];14     15     for (NSDictionary *dic in array) {16         Student *stu = [[Student alloc]initWithDictionary:dic];17         [arr addObject:stu];18     }19     20     for (Student *stu in arr) {21         NSLog(@"%@",stu);22     }23 }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.