一、添加ASIHttpRequest
方法:http://blog.csdn.net/debug__boy/article/details/7485094
二、添加SBJson
SBJson的开放源码在github上托管。
三、以上工作完成之后,下面就是敲代码了
(1)首先加入头文件
#import "ASIHTTPRequest.h"
#import "SBJson.h"
(2)Http请求
NSURL *url = [NSURL URLWithString:@"http://......."];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous]; //对应的同步请求[request startSynchronous];
(3)请求完成后,会调用requestFinished方法
-(void) requestFinished: (ASIHTTPRequest *) request {
NSString *responseData = [request responseString]; //获得服务器response的数据
//解析Json数据....
}
(4)Json数据处理
(a)处理一条记录
测试用的字符串是:responseData =@"{\"user\":{\"id\":21,\"name\":\"xxx\"}}";
SBJsonParser * parser = [[SBJsonParser alloc] init];
NSError * error = nil;
NSMutableDictionary *jsonDic = [parser objectWithString:responseString error:&error];
NSLog(@"%@",[jsonDic objectForKey:@"user" ]);
NSMutableDictionary * dicUserInfo = [jsonDic objectForKey:@"user"];
NSLog(@"%@",[dicUserInfo objectForKey:@"id"]);
NSLog(@"%@",[dicUserInfo objectForKey:@"name"]);
(b)处理多条记录
测试用的字符串是:
SBJsonParser * parser = [[SBJsonParser alloc] init];
NSError * error = nil;
NSArray *memberList = [parser objectWithString:responseString error:&error];
for(NSDictionary *member in memberList)
{
NSLog(@"dibitsID = %d", [[member objectForKey:@"dibitsID"] integerValue]);
NSLog(@"type = %d", [[member objectForKey:@"type"] integerValue]);
NSLog(@"time = %@", [member objectForKey:@"updated"]);
NSLog(@"\n");
}