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

苹果开发 笔记(77)NSJSONSerialization

发布时间:2020-12-16 19:04:09 所属栏目:百科 来源:网络整理
导读:NSJSONSerialization 是解析json的自带的ios 类,使用它可以解析json 的信息。除了读取xml外,json也是比较常用的一些数据操作。之前用了一下,现在记录一下。 下面记录一下json的页面信息,以获取天气的信息json来解析一下。 {" weatherinfo ": {" city ":

NSJSONSerialization 是解析json的自带的ios 类,使用它可以解析json 的信息。除了读取xml外,json也是比较常用的一些数据操作。之前用了一下,现在记录一下。

下面记录一下json的页面信息,以获取天气的信息json来解析一下。

{"weatherinfo":{"city":"北京","cityid":"101010100","temp":"9","WD":"西南风","WS":"2级","SD":"22%","WSE":"2","time":"10:45","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB","njd":"暂无实况","qy":"1014"}}

使用NSData 直接来读取远程的数据

NSString *jsonPath  =@"http://www.weather.com.cn/adat/sk/101010100.html";
 NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:jsonPath]];    
 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
 NSDictionary *weatherDic =  [dic objectForKey:@"weatherinfo"];
 NSLog(@"JSON 城市 %@",[weatherDic objectForKey:@"city"]);
 NSLog(@"JSON 城市ID %@",[weatherDic objectForKey:@"cityid"]);
 NSLog(@"JSON 温度 %@",[weatherDic objectForKey:@"temp"]);

使用NSURLConnection 读取json的信息

NSURLRequest *resuest  = [NSURLRequest requestWithURL:[NSURL URLWithString:jsonPath]];

 [NSURLConnection sendAsynchronousRequest:resuest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response,NSData *data,NSError *connectionError){       
      NSError *error = nil;
      NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
      NSDictionary *weatherDic =  [dic objectForKey:@"weatherinfo"];
      NSLog(@"JSON 城市 %@",[weatherDic objectForKey:@"city"]);
      NSLog(@"JSON 城市ID %@",[weatherDic objectForKey:@"cityid"]);
      NSLog(@"JSON 温度 %@",[weatherDic objectForKey:@"temp"]);    
    }];

NSData 也是使用频繁的一个类,经常会涉及到。

(编辑:李大同)

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

    推荐文章
      热点阅读