0

我开始构建通过 http 请求从外部服务器读取的登录表单我需要解析 json 结果以获取用户名

- (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);
}

我得到这个结果:

{"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 ","图片":"","init":"mohammed.abdelrasoul@gmail.com","数据":"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":"亚洲/利雅得","block":{"webform":{"client-block-88":1}},"form_build_id":"form-3ae73833f08accc7abe5517347ea87eb","contact":0,"roles":{"2" :"认证用户"}}}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"}}}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"}}}client-block-88":1}},"form_build_id":"form-3ae73833f08accc7abe5517347ea87eb","contact":0,"roles":{"2":"authenticated user"}}}client-block-88":1}},"form_build_id":"form-3ae73833f08accc7abe5517347ea87eb","contact":0,"roles":{"2":"authenticated user"}}}

或者,为了便于阅读而格式化:

{
   "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"
      }
   }
}

我如何获取对象数据或解析结果以获取用户名任何帮助或示例将不胜感激

4

4 回答 4

2

您需要使用 NSJSONSerialization 类方法 JSONObjectWithData:options:error: 创建一个 NSDictionary:

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

这将使您能够查看字典,这将更容易阅读。看起来您需要使用 objectForKey:@"sessid" 来获取用户,然后使用 objectForKey@"user",然后使用 objectForKey:@"name" 来获取名称。

于 2012-11-11T22:16:49.413 回答
1

查看这个解析 json 的框架。https://github.com/stig/json-framework/

另请查看此答案iPhone/iOS JSON parsing tutorial。你会找到一个教程的链接,你可以通过它来熟悉 ios 中的 json 解析。

于 2012-11-11T22:14:24.517 回答
0

要扩展rdelmar 的答案(我认为您应该接受),您可以使用NSJSONSerialization然后导航NSDictionary结果以提取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);
}

或者,如果使用最新版本的 Xcode,您可以用objectForKey更简洁的Modern Objective-C语法替换这些引用:

    NSDictionary *userDictionary = jsonDict[@"user"];
    NSString *userName = userDictionary[@"name"];
于 2012-11-12T03:09:43.337 回答
0

请参阅此答案和一些代码:

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

    }
于 2012-11-11T22:22:34.553 回答