NSJSONSerialization

本文详细介绍了如何使用Objective-C中的NSJSONSerialization类将JSON字符串转换为Objective-C的字典对象,以及如何将Objective-C的数据结构转换为JSON格式进行序列化。重点展示了数据加载、解析、存储和打印的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

json -> object
  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. }  

object -> 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.     }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值