如何在目标c中获得json数据的响应?

时间:2015-11-07 10:03:23

标签: ios objective-c json

我使用这段代码在url中发布我的数据。

NSString *urlString = [NSString stringWithFormat:@"company_name=%@&email_id=%@&password=%@",_CompanyName.text,_Email.text, _Password.text];
NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[urlString length]];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc]init];
NSString *url = @"http://dev1.brainpulse.org/quickmanhelp/webservice/api.php?act=registration";
[req setURL:[NSURL URLWithString:url]];
[req setHTTPMethod:@"POST"];
[req setValue:postLength forHTTPHeaderField:@"Content-Length"];
[req setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[req setHTTPBody:[urlString dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue currentQueue] completionHandler:
    ^(NSURLResponse *reponse , NSData *data, NSError *error){
         NSError *errre1;
         dictLogin=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&errre1];
         NSLog(@"result is%@ :",dictLogin);
         NSLog(@"result is%@ :",urlString);
         [user setObject:[dictLogin objectForKey:@"company_name"] forKey:@"company_name"];
         [user setObject:[dictLogin objectForKey:@"email_id"] forKey:@"email_id"];
         [user setObject:[dictLogin objectForKey:@"passord"] forKey:@"password"];

现在我不知道在我要登录屏幕时得到回应,

JSON

result : "Successful"
data
0
user_id : "1"
email_id : "gupta.monu4@gmail.com"
password : "monu"
phone_no : ""
user_type : "admin"
company_name : "Brainpulse"

这是我的json结构。

1 个答案:

答案 0 :(得分:1)

检查这样可以避免崩溃和内存泄漏

  // create the one global array for save
  NSMutableArray *user =[NSMutableArray new];

dictLogin=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&errre1];

if (dictLogin)
{
// serilize your data
    if ([[dictLogin objectForKey:@"result"] isEqualToString:"Successful"])
    {

        [user removeAllobjects];
       // assign into one array
        NSArray *TempArray = dictLogin[@"data"];

        for (NSDictionary *tmp in TempArray)
         {
          // careate one temporary dictionary
           NSMutableDictionary *tmpDict = [NSMutableDictionary new];


      // store your data to Dictionary or array
        [tmpDict setObject:[tmp objectForKey:@"company_name"] forKey:@"company_name"];
         [tmpDict setObject:[tmp objectForKey:@"email_id"] forKey:@"email_id"];

        if ([tmp objectForKey:@"passord"] != nil) {
         [tmpDict setObject:[tmp objectForKey:@"passord"] forKey:@"password"];
 }


            [user addobject:tmpDict];

            // then use your data where u need

     }
     else
     {
       // show the failure report
      }
}
else
{
 // show the failure report
}