您的位置:首页 > 理论基础 > 计算机网络

iOS网络开发——JSON数据解码(使用NSJSONSerialization)

2015-08-28 13:32 579 查看
下面我们通过一个案例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:。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: