ASIHttpRequest和json-framework实现json解析(iOS客户端)

来源:互联网 发布:php memorylimit 编辑:程序博客网 时间:2024/05/20 16:11



 

这篇日志我会写一个客户端json解析的小例子,下篇日志我会写服务器端的代码。

1、进行必要的准备工作。

下载ASIHttpRequest类库,github上有,https://github.com/pokeb/asi-http-request/

下载json-framework,github上也有,https://github.com/stig/json-framework/

2、将下载的类库添加到Xcode项目中

3、添加framework

libz.dylib

CFNetwork.framework

SenTestingKit.framework

SystemConfiguration.framework

MobileCoreServices.framework

4、上面的步骤做好之后,下面就是关键了。

Plain代码 
  1. NSURL *url = [NSURL URLWithString:@"http://......(这里是服务端的url)/Default.aspx"];  
  2. ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];  
  3. [request startSynchronous];  
  4. NSString *response = [request responseString];  
  5. NSLog(@"%@",response);  //这里输出一下,看得到的json字符串是否正确  


  1.  jsonString = [[NSString alloc] initWithString:@"{\"userInfo\":{\"userName\":\"徐泽宇\",\"sex\":\"男\"}}"];  
  2.     NSLog(@"正在解析json字符串是:%@",jsonString);  
  3.       
  4.     SBJsonParser * parser = [[SBJsonParser alloc] init];  
  5.     NSError * error = nil;  
  6.     NSMutableDictionary *jsonDic = [parser objectWithString:jsonString error:&error];  
  7.     NSMutableDictionary * dicUserInfo = [jsonDic objectForKey:@"userInfo"];  
  8.       
  9.     NSLog(@"%@",[jsonDic objectForKey:@"userInfo" ]);  
  10.     NSLog(@"%@",[dicUserInfo objectForKey:@"userName"]);  
  11.     NSLog(@"%@",[dicUserInfo objectForKey:@"sex"]);  






  1. NSMutableArray *data = [response JSONValue]; //这里得到的json字符串里面含有多个Dictionary  
  2. for (NSDictionary *dictionary in data) //对NSMutableArray进行遍历  
  3. {          
  4.     NSLog(@"%@,%@",[dictionary objectForKey:@"number"],[dictionary objectForKey:@"name"]);  
  5. }  
5、最终在控制台就会输出解析好的键值对应的字符串了。
原创粉丝点击