NSJSONSerialization

来源:互联网 发布:js object对象 编辑:程序博客网 时间:2024/05/24 00:21

自从iOS5.0以后,苹果推出了SDK自带的JSON解决方案NSJSONSerialization,这是一个非常好用的JSON生成和解析工具,效率也是比其他第三方开源项目的高很多,效率测试见后面。

NSJSONSerialization主要的方法包括NSDictionary、NSArray与json格式的转换,判断一个data是不是json。通过豆瓣一段代码来看:

#define kGlobalQueue    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)#define kDoubanUrl      @"http://douban.fm/j/mine/playlist?type=n&h=&channel=0&from=mainsite&r=4941e23d79"-(void) loadJsonData:(NSURL *)url{    dispatch_async(kGlobalQueue, ^{        NSData *data = [NSData dataWithContentsOfURL:url];        [self performSelectorOnMainThread:@selector(parseJsonData:) withObject:data waitUntilDone:NO];    });}-(void) parseJsonData:(NSData *)data{    NSError *error;
//将json转化成NSArray、NSDictionary
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];    if (json == nil) {        NSLog(@"json parse failed \r\n");        return;    }    NSArray *songArray = [json objectForKey:@"song"];    NSLog(@"song collection: %@\r\n",songArray);    _song = songArray;    self.songIndex = 0;    NSDictionary *song = [songArray objectAtIndex:0];    NSLog(@"song info: %@\t\n",song);}
//通过将data转化为json
NSDictionary *song = [NSDictionary dictionaryWithObjectsAndKeys:@"i can fly",@"title",@"4012",@"length",@"Tom",@"Singer", nil];    if ([NSJSONSerialization isValidJSONObject:song])    {        NSError *error;        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:song options:NSJSONWritingPrettyPrinted error:&error];        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];        NSLog(@"json data:%@",json);    }
关于苹果系统自带的json解析器和第三方的库的解析速度对比见:http://blog.csdn.net/arthurchenjs/article/details/7009995

0 0
原创粉丝点击