加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

NSJSONSerialization

发布时间:2020-12-16 19:50:05 所属栏目:百科 来源:网络整理
导读:ios5中apple增加了解析JSON的api——NSJSONSerialization。网上已经有人做过测试,NSJSONSerialization在效率上完胜SBJSON、TouchJSON、YAJL、JSONKit、NextiveJson。详情见这里。既然apple为我们提供了这么良好的工具,我们没理由不用吧。 NSJSONSerializat

ios5中apple增加了解析JSON的api——NSJSONSerialization。网上已经有人做过测试,NSJSONSerialization在效率上完胜SBJSON、TouchJSON、YAJL、JSONKit、NextiveJson。详情见这里。既然apple为我们提供了这么良好的工具,我们没理由不用吧。  NSJSONSerialization提供了将JSON数据转换为Foundation对象(一般都是NSDictionary和NSArray)和Foundation对象转换为JSON数据(可以通过调用isValidJSONObject来判断Foundation对象是否可以转换为JSON数据)。 

 下面提供一个从豆瓣电台下载的json数据转换的代码

  1. ViewCode
  2. #definekGlobalQueuedispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)
  3. #definekDoubanUrl@"http://douban.fm/j/mine/playlist?type=n&h=&channel=0&from=mainsite&r=4941e23d79"
  4. -(void)loadJsonData:(NSURL*)url
  5. {
  6. dispatch_async(kGlobalQueue,^{
  7. NSData*data=[NSDatadataWithContentsOfURL:url];
  8. [selfperformSelectorOnMainThread:@selector(parseJsonData:)withObject:datawaitUntilDone:NO];
  9. });
  10. }
  11. -(void)parseJsonData:(NSData*)data
  12. {
  13. NSError*error;
  14. NSDictionary*json=[NSJSONSerializationJSONObjectWithData:dataoptions:kNilOptionserror:&error];
  15. if(json==nil){
  16. NSLog(@"jsonparsefailedrn");
  17. return;
  18. NSArray*songArray=[jsonobjectForKey:@"song"];
  19. NSLog(@"songcollection:%@rn",songArray);
  20. _song=songArray;
  21. self.songIndex=0;
  22. NSDictionary*song=[songArrayobjectAtIndex:0];
  23. NSLog(@"songinfo:%@tn",song);
  24. }
Foundation对象转换为js
  1. ViewCode
  2. NSDictionary*song=[NSDictionarydictionaryWithObjectsAndKeys:@"icanfly",@"title",@"4012",@"length",@"Tom",@"Singer",nil];
  3. if([NSJSONSerializationisValidJSONObject:song])
  4. {
  5. NSError*error;
  6. NSData*jsonData=[NSJSONSerializationdataWithJSONObject:songoptions:NSJSONWritingPrettyPrintederror:&error];
  7. NSString*json=[[NSStringalloc]initWithData:jsonDataencoding:NSUTF8StringEncoding];
  8. NSLog(@"jsondata:%@",json);
  9. }
on数据

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读