Search code examples
iosjsonrestnsscanner

How to parse JSON response from Rest API


I am working on an app that will parse data from a Rest API. As I haven't done this before, I was wondering if NSScanner or NSRange would work for this. Here is an example using NSScanner for such purposes. It's a small string so it doesn't take much code, so it seemed like a quick and dirty option. Is there an easier and quicker way to do this?

- (void)GetAliasName:(NSString *)cno selector:(NSString*)selectorName completionHandler:(void (^)(NSDictionary *, NSError *))handler

{

NSMutableDictionary *d = [[NSMutableDictionary alloc] init];

[d setValue:interface forKey:@"interface"];

[d setValue:@"GetAlias" forKey:@"method"];

NSMutableDictionary *p = [[NSMutableDictionary alloc] init];

cno = [[NSUserDefaults standardUserDefaults] objectForKey:@"cno"];

[p setValue:cno forKey:@"cno"];

[p setValue:selectorName forKey:@"selector"];

[d setValue:p forKey:@"parameters"];

NSData *data = [NSJSONSerialization dataWithJSONObject:d options:0 error:nil];

[self load:data completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

    NSLog(@"done");

    NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSLog(@"GetAlias RAW response = %@", s);

    if (apiConditions)
    {
        dispatch_async(dispatch_get_main_queue(),
                       ^{
                           [hud hide:YES];
                           [MBProgressHUD hideHUDForView:self.view animated:YES];
                           UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"No network connection or no data found" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                           [alert show];
                           NSLog(@"data is NIL");
                       });


    }
    else
    {
        NSDictionary *d = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        handler(d, error);

            //scans for aliasname
            NSString *match = @"AliasName\": \"";
            NSString *preTel;
            NSString *postTel;

            NSScanner *scanner = [NSScanner scannerWithString:s];
            [scanner scanUpToString:match intoString:&preTel];

            [scanner scanString:match intoString:nil];
            postTel = [s substringFromIndex:scanner.scanLocation];


            //removes newlines, characters, and whitespaces from aliasname
            NSCharacterSet *trim = [NSCharacterSet characterSetWithCharactersInString:@"}]\""];
            postTel = [[postTel componentsSeparatedByCharactersInSet: trim] componentsJoinedByString: @""];
            postTel = [[postTel componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]] componentsJoinedByString: @""];


            NSLog(@"postTel: %@", postTel);
            NSString *docno = [[NSUserDefaults standardUserDefaults] objectForKey:@"docno"];

            //if docno is filled in, look up TR by docno
            if ([docno isEqual: @""])
            {

            [self GetTR:(NSString*)postTel customStatus:customStatus completionhandler:^(NSDictionary *dictionary, NSError *error) {
                nil;
            }];

}
}];
}

Solution

  • There is NSJSONSerialization which is built for this.

    Use it as follows:

    NSError *error = nil;
    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
    NSString *aliasName = dictionary[@"AliasName"];
    

    Edit

    Since you already use this, and have dictionary, the only step you needed was to access dictionary with needed key(last step).