Cocos2d/x 解析服务器JSON数据

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];



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值