您的位置:首页 > 理论基础 > 计算机网络

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

2012-07-18 14:25 633 查看



这篇日志我会写一个客户端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代码

NSURL *url = [NSURL URLWithString:@"http://......(这里是服务端的url)/Default.aspx"];

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];

[request startSynchronous];

NSString *response = [request responseString];

NSLog(@"%@",response); //这里输出一下,看得到的json字符串是否正确

jsonString = [[NSString alloc] initWithString:@"{\"userInfo\":{\"userName\":\"徐泽宇\",\"sex\":\"男\"}}"];

NSLog(@"正在解析json字符串是:%@",jsonString);



SBJsonParser * parser = [[SBJsonParser alloc] init];

NSError * error = nil;

NSMutableDictionary *jsonDic = [parser objectWithString:jsonString error:&error];

NSMutableDictionary * dicUserInfo = [jsonDic objectForKey:@"userInfo"];



NSLog(@"%@",[jsonDic objectForKey:@"userInfo" ]);

NSLog(@"%@",[dicUserInfo objectForKey:@"userName"]);

NSLog(@"%@",[dicUserInfo objectForKey:@"sex"]);


NSMutableArray *data = [response JSONValue]; //这里得到的json字符串里面含有多个Dictionary

for (NSDictionary *dictionary in data) //对NSMutableArray进行遍历

{

NSLog(@"%@,%@",[dictionary objectForKey:@"number"],[dictionary objectForKey:@"name"]);

}

5、最终在控制台就会输出解析好的键值对应的字符串了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: