如何解析Rest API中的JSON响应

时间:2015-03-27 13:37:46

标签: ios json rest nsscanner

我正在开发一个解析来自Rest API的数据的应用。由于我之前没有这样做,我想知道NSScanner或NSRange是否适用于此。以下是使用NSScanner进行此类目的的示例。它是一个小字符串,因此它不需要太多代码,所以它看起来像一个快速而肮脏的选项。是否有更简单快捷的方法来做到这一点?

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

}
}];
}

1 个答案:

答案 0 :(得分:2)

为此构建NSJSONSerialization

按如下方式使用:

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

修改

由于您已经使用了这个并且有字典,因此您需要的唯一步骤是使用所需的密钥访问字典(最后一步)。