JSON格式数据的好处就不用说了,对于手机客户端,使用JSON.h 来进行解析,相当便利。
蚂蚁使用ObjectC的代码来进行服务器返回数据的处理(cocos2d-x支持混编,就不再纠结是否有C++的处理方式了)
贴代码出来:
//用户注册,上送 邮箱、用户名、密码
-(BOOL)userReg{
//直接创建一个上送用的json格式数据
NSString *postStr = [NSString stringWithstring:@"regdata={\"email\":\"mayi@qq.com\",\"name\":\"mafengwoo\",\"password\":\"123456\"}"];
//码制转换
NSData *postData = [encodingStr dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://www.mafengwoo.com/reg.php"]];
[request setHTTPMethod:@"POST"];
[request setTimeoutInterval: 20];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSHTTPURLResponse *urlResponse=nil;
NSError *errorr=nil;
NSData *receivedData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponse
error:&errorr];
//JSON数据解析
NSString *results=[[NSString alloc]initWithBytes:[receivedData bytes] length:[receivedData length] encoding:NSUTF8StringEncoding];
NSLog(@"-mayi- %@",results);
NSDictionary*dic = [results JSONValue];
NSString *sStatus = [dic objectForKey:@"status"];
NSLog(@"Status is :%@", sStatus);
return YES;
}
注:
1、如果返回的数据中有嵌套JSON数据,则用NSDictionary 来获取
NSDictionary *dicReceipt = [dic objectForKey:@"receipt"];
2、JSON的键值默认是字符串的,如果要接受数字的键值数据,则用:
int iStatus = [[dic objectForKey:@"status" ] intValue];