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":"[email protected]","mail":"[email protected]","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":"[email protected]","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":"[email protected]",
      "mail":"[email protected]",
      "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":"[email protected]",
      "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

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 Agreed. Obviously, you probably should only use that NSJSONReadingMutableContainers option if you really need the mutable containers.
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.

1 Comment

Thanks guys all the answers are more helpful :)
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];

    }

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.