如何解析来自 Rest API 的 JSON 响应

How to parse JSON response from Rest API

我正在开发一个应用程序,它将解析来自 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;
            }];

}
}];
}

NSJSONSerialization 是为此而建的。

按如下方式使用:

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

编辑

由于您已经在使用它并拥有字典,因此您唯一需要的步骤就是使用所需的键访问字典(最后一步)。