iOS網路開發——JSON資料解碼(使用NSJSONSerialization)

來源:互聯網
上載者:User
下面我們通過一個案例MyNotes學習一下NSJSONSerialization的用法。這裡重新設計資料結構為JSON格式,

其中備忘錄資訊Notes.json檔案的內容如下:

{"ResultCode":0,"Record":[{"ID":"1","CDate":"2012-12-23","Content":"發布iOSBook0","UserID":"tony"},{"ID":"2","CDate":"2012-12-24","Content":"發布iOSBook1","UserID":"tony"},{"ID":"3","CDate":"2012-12-25","Content":"發布iOSBook2","UserID":"tony"},{"ID":"4","CDate":"2012-12-26","Content":"發布iOSBook3","UserID":"tony"},{"ID":"5","CDate":"2012-12-27","Content":"發布iOSBook4","UserID":"tony"}]}
事實上,NSJSONSerialization使用起來更為簡單,只要能確定你的項目使用了iOS 5 SDK就可以了。修改視圖
控制器MasterViewController的viewDidLoad方法,具體代碼如下:

- (void)viewDidLoad{[super viewDidLoad];self.navigationItem.leftBarButtonItem = self.editButtonItem;self.detailViewController = (DetailViewController *)[[self.splitViewController.viewControllers lastObject] topViewController];[[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(reloadView:)  name:@"reloadViewNotification"  object:nil];//路徑,實際開發中要請求伺服器端NSString* path = [[NSBundle mainBundle] pathForResource:@"Notes" ofType:@"json"];NSData *jsonData = [[NSData alloc] initWithContentsOfFile:path];NSError *error;//options參數指定瞭解下JSON的模式://NSJSONReadingMutableContainers -指定解析返回的是可變的數組或字典.(這個常量是合適的選擇)//NSJSONReadingMutableLeaves。指定分葉節點是可變字串。//NSJSONReadingAllowFragments。指定頂級節點可以不是數組或字典id jsonObj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];if (!jsonObj || error) {NSLog(@"JSON解碼失敗");}self.listData = [jsonObj objectForKey:@"Record"];}
此外,NSJSONSerialization還提供了JSON編碼的方法:dataWithJSONObject:options:error:和
writeJSONObject:toStream:options:error:。


相關文章

聯繫我們

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