iOS开发基本技能之JSON

现下移动终端开发主要是两大阵容,Android和iOS。

iOS比较简单,iOS5后,应用框架里自带了NSJSONSerialization类进行JSON解析(效率完胜其他开源的SDK)。小例子两个:

1)解析网络数据

//使用TouchJson来解析北京的天气
- (IBAction)btnPressTouchJson:(id)sender {
//获取API接口
NSURL *url = [NSURL URLWithString:@"http://m.weather.com.cn/data/101010100.html"];
//定义一个NSError对象,用于捕获错误信息
NSError *error;
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
NSLog(@"jsonString--->%@",jsonString);
//将解析得到的内容存放字典中,编码格式为UTF8,防止取值的时候发生乱码
NSDictionary *rootDic = [[CJSONDeserializer deserializer] deserialize:[jsonString dataUsingEncoding:NSUTF8StringEncoding] error:&error];
//因为返回的Json文件有两层,去第二层内容放到字典中去
NSDictionary *weatherInfo = [rootDic objectForKey:@"weatherinfo"];
NSLog(@"weatherInfo--->%@",weatherInfo);
//取值打印
txtView.text = [NSString stringWithFormat:@"今天是 %@ %@ %@ 的天气状况是:%@ %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]];
}

2)解析和组装JSON串
解析

-(void) parseJsonData:(NSData *)data
{
NSError *error;
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);
}

组装

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);
}

参考:http://blog.sina.com.cn/s/blog_6737a6170101fd9z.html
http://blog.csdn.net/enuola/article/details/7903632/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值