Cocos2d/x 解析服务器JSON数据

来源:互联网 发布:动感单车品牌知乎 编辑:程序博客网 时间:2024/05/16 04:10

JSON格式数据的好处就不用说了,对于手机客户端,使用JSON.h 来进行解析,相当便利。

蚂蚁使用ObjectC的代码来进行服务器返回数据的处理(cocos2d-x支持混编,就不再纠结是否有C++的处理方式了)


贴代码出来:

//用户注册,上送 邮箱、用户名、密码

-(BOOL)userReg{      

    //直接创建一个上送用的json格式数据

   NSString *postStr      = [NSStringstringWithstring:@"regdata={\"email\":\"mayi@qq.com\",\"name\":\"mafengwoo\",\"password\":\"123456\"}"];

    //码制转换

    NSData *postData = [encodingStr dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

   NSString *postLength = [NSStringstringWithFormat:@"%d", [postDatalength]];

    NSMutableURLRequest *request = [[[NSMutableURLRequestalloc] init] autorelease];

    [requestsetURL:[NSURLURLWithString:@"http://www.mafengwoo.com/reg.php"]];

    [requestsetHTTPMethod:@"POST"];

    [request setTimeoutInterval:20];

    [requestsetValue:postLength forHTTPHeaderField:@"Content-Length"];

    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    [requestsetHTTPBody:postData];

    

   NSHTTPURLResponse *urlResponse=nil;

   NSError *errorr=nil;

   NSData *receivedData = [NSURLConnectionsendSynchronousRequest:request

                                                returningResponse:&urlResponse

                                                            error:&errorr];

    

   //JSON数据解析

    NSString *results=[[NSStringalloc]initWithBytes:[receivedDatabytes] length:[receivedDatalength] encoding:NSUTF8StringEncoding];

   NSLog(@"-mayi- %@",results);

   NSDictionary*dic = [results JSONValue];

    

   NSString *sStatus = [dic objectForKey:@"status"];

   NSLog(@"Status is :%@", sStatus);

    returnYES;

}


注:

1、如果返回的数据中有嵌套JSON数据,则用NSDictionary 来获取

NSDictionary *dicReceipt = [dicobjectForKey:@"receipt"];


2、JSON的键值默认是字符串的,如果要接受数字的键值数据,则用:

int  iStatus = [[dicobjectForKey:@"status" ]intValue];



原创粉丝点击