下面我們通過一個案例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:。