0

am starting to build login form reading from external server via http request i need to parse json result to get user name

- (IBAction)getlogin:(UIButton *)sender {
    NSString *rawStrusername = [NSString stringWithFormat:@"username=%@",_username.text];
    NSString *rawStrpassword = [NSString stringWithFormat:@"password=%@",_password.text];
    NSString *post = [NSString stringWithFormat:@"%@&%@", rawStrusername, rawStrpassword];
    // NSString *post = @"rawStrusername&rawStrpassword";
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    /* NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; */

    NSURL *url = [NSURL URLWithString:@"http://www.othaimmarkets.com/my_services_path/user/login.json"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    [request setHTTPMethod:@"POST"];

    /* [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; */

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

    NSURLResponse *response;
    NSError *err;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

    NSLog(@"responseData: %@", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);
    //NSLog(@"responseData: %@", responseData);
}

I get this result:

{"sessid":"g2ev7til6d750ducrkege0cbj2","session_name":"SESS02795057fe9e6b2fc0777bf4057b248f","user":{"uid":"617","name":"mohammed.abdelrasoul@gmail.com","mail":"mohammed.abdelrasoul@gmail.com","mode":"0","sort":"0","threshold":"0","theme":"","signature":"","signature_format":"0","created":"1316602317","access":"1352643854","login":"1352666338","status":"1","timezone":"10800","language":"ar","picture":"","init":"mohammed.abdelrasoul@gmail.com","data":"a:5:{s:18:\"country_iso_code_2\";s:2:\"SA\";s:13:\"timezone_name\";s:11:\"Asia/Riyadh\";s:5:\"block\";a:1:{s:7:\"webform\";a:1:{s:15:\"client-block-88\";i:1;}}s:13:\"form_build_id\";s:37:\"form-3ae73833f08accc7abe5517347ea87eb\";s:7:\"contact\";i:0;}","country_iso_code_2":"SA","timezone_name":"Asia/Riyadh","block":{"webform":{"client-block-88":1}},"form_build_id":"form-3ae73833f08accc7abe5517347ea87eb","contact":0,"roles":{"2":"authenticated user"}}}

Or, formatted for the sake of legibility:

{
   "sessid":"g2ev7til6d750ducrkege0cbj2",
   "session_name":"SESS02795057fe9e6b2fc0777bf4057b248f",
   "user":{
      "uid":"617",
      "name":"mohammed.abdelrasoul@gmail.com",
      "mail":"mohammed.abdelrasoul@gmail.com",
      "mode":"0",
      "sort":"0",
      "threshold":"0",
      "theme":"",
      "signature":"",
      "signature_format":"0",
      "created":"1316602317",
      "access":"1352643854",
      "login":"1352666338",
      "status":"1",
      "timezone":"10800",
      "language":"ar",
      "picture":"",
      "init":"mohammed.abdelrasoul@gmail.com",
      "data":"a:5:{s:18:\"country_iso_code_2\";s:2:\"SA\";s:13:\"timezone_name\";s:11:\"Asia/Riyadh\";s:5:\"block\";a:1:{s:7:\"webform\";a:1:{s:15:\"client-block-88\";i:1;}}s:13:\"form_build_id\";s:37:\"form-3ae73833f08accc7abe5517347ea87eb\";s:7:\"contact\";i:0;}",
      "country_iso_code_2":"SA",
      "timezone_name":"Asia/Riyadh",
      "block":{
         "webform":{
            "client-block-88":1
         }
      },
      "form_build_id":"form-3ae73833f08accc7abe5517347ea87eb",
      "contact":0,
      "roles":{
         "2":"authenticated user"
      }
   }
}

how i can get the objects data or parse the result to get user name any help or examples will be appreciated

Rob
  • 415,655
  • 72
  • 787
  • 1,044

4 Answers4

2

You need to use the NSJSONSerialization class method, JSONObjectWithData:options:error: to create an NSDictionary:

NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
if (! error) {
    NSLog(@"%@",jsonDict);
}else{
    NSLog(@"%@",error.localizedDescription);
}

This will get you to the point where you can look at the dictionary, which will be easier to read. It looks like you need to use objectForKey:@"sessid" to get you to user, then objectForKey@"user", then objectForKey:@"name" to get you to the name.

rdelmar
  • 103,982
  • 12
  • 207
  • 218
  • +1 Agreed. Obviously, you probably should only use that `NSJSONReadingMutableContainers` option if you really need the mutable containers. – Rob Nov 12 '12 at 13:51
1

Check out this framework for parsing json. https://github.com/stig/json-framework/

Also check out this answer iPhone/iOS JSON parsing tutorial. You'll find a link to a tutorial you can do to get acquainted with json parsing in ios.

Community
  • 1
  • 1
NikosM
  • 1,131
  • 7
  • 9
0

See this answer and some code :

NSMutableData *data; // Contains data received from the URL connection declares in header


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)dataIn 
{ 
// Do it this way because connection doesn't guarantee all the data is in
POLLog(@" Tide View connection");
[data appendData:dataIn];
}


- (void) connectionDidFinishLoading:(NSURLConnection *) conn 
{

NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *results = [jsonString JSONValue]; // This is a new category added to the NSString by SBJSON
//100 parameters
for (int n=0;n<=100;n++)
    {
        // Get all the returned results
        params[n] = [[results objectForKey:[NSString stringWithFormat:@"param%d",n]] floatValue];

    }
Community
  • 1
  • 1
Nick T
  • 897
  • 8
  • 30
0

To expand upon rdelmar's answer (which I think you should accept), you can use NSJSONSerialization and then navigate the NSDictionary results to extract the userName:

NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData
                                                         options:0
                                                           error:&error];
if (error == nil) {
    NSDictionary *userDictionary = [jsonDict objectForKey:@"user"];
    NSString *userName = [userDictionary objectForKey:@"name"];

    // do what you need with the userName

} else {
    NSLog(@"%@",error.localizedDescription);
}

Or if using the latest version of Xcode, you can replace those objectForKey references with the even more concise Modern Objective-C syntax:

    NSDictionary *userDictionary = jsonDict[@"user"];
    NSString *userName = userDictionary[@"name"];
Community
  • 1
  • 1
Rob
  • 415,655
  • 72
  • 787
  • 1,044