NSJSONSerialization介绍 系统自带的JSon解析 NSdate转化为json数据
Ios5中apple增加了解析JSON的api——NSJSONSerialization。网上已经有人做过测试,NSJSONSerialization在效率上完胜SBJSON、TouchJSON、YAJL、JSONKit、NextiveJson。详情见这里。既然apple为我们提供了这么良好的工具,我们没理由不用吧。
NSJSONSerialization提供了将JSON数据转换为Foundation对象(一般都是NSDictionary和NSArray)和Foundation对象转换为JSON数据(可以通过调用isValidJSONObject来判断Foundation对象是否可以转换为JSON数据)。
下面提供一个从豆瓣电台下载的json数据转换的代码
1 #define kGlobalQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0) 2 #define kDoubanUrl @"http://douban.fm/j/mine/playlist?type=n&h=&channel=0&from=mainsite&r=4941e23d79" 3 -(void) loadJsonData:(NSURL *)url 4 { 5 dispatch_async(kGlobalQueue, ^{ 6 NSData *data = [NSData dataWithContentsOfURL:url]; 7 [self performSelectorOnMainThread:@selector(parseJsonData:) withObject:data waitUntilDone:NO]; 8 }); 9 } 10 -(void) parseJsonData:(NSData *)data 11 { 12 NSError *error; 13 NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 14 if (json == nil) { 15 NSLog(@"json parse failed \r\n"); 16 return; 17 } 18 NSArray *songArray = [json objectForKey:@"song"]; 19 NSLog(@"song collection: %@\r\n",songArray); 20 21 _song = songArray; 22 self.songIndex = 0; 23 NSDictionary *song = [songArray objectAtIndex:0]; 24 NSLog(@"song info: %@\t\n",song); 25 }
Foundation对象转换为json数据
1 NSDictionary *song = [NSDictionary dictionaryWithObjectsAndKeys:@"i can fly",@"title",@"4012",@"length",@"Tom",@"Singer", nil]; 2 if ([NSJSONSerialization isValidJSONObject:song]) 3 { 4 NSError *error; 5 NSData *jsonData = [NSJSONSerialization dataWithJSONObject:song options:NSJSONWritingPrettyPrinted error:&error]; 6 NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 7 NSLog(@"json data:%@",json); 8 }
NSJSONReadingMutableContainers:返回可变容器,NSMutableDictionary或NSMutableArray。
NSJSONReadingMutableLeaves:返回的JSON对象中字符串的值为NSMutableString,目前在iOS 7上测试不好用,应该是个bug,参见:
http://stackoverflow.com/questions/19345864/nsjsonreadingmutableleaves-option-is-not-working
NSJSONReadingAllowFragments:允许JSON字符串最外层既不是NSArray也不是NSDictionary,但必须是有效的JSON Fragment。例如使用这个选项可以解析 @“123” 这样的字符串。参见:
http://stackoverflow.com/questions/16961025/nsjsonserialization-nsjsonreadingallowfragments-reading
NSJSONWritingPrettyPrinted:的意思是将生成的json数据格式化输出,这样可读性高,不设置则输出的json字符串就是一整行

浙公网安备 33010602011771号