使用Objective-c解析JSON url中的信息



我正在尝试编写一段使用reddits JSON格式的代码。我打算访问网址:http://www.reddit.com/r/pics/new/.json,搜索字符串:"title":"并将从那里到下一个撇号的所有内容都写入日志,直到所有标题都写入日志。

到目前为止,我有这个,但我没有得到任何日志输出。有人能帮我吗?

- (void)viewDidLoad
{
    NSString *redditString = @"http://www.reddit.com/r/pics/new/.json";
    NSURL *redditURL = [NSURL URLWithString:redditString];
    NSError *error;
    NSCharacterSet *commaSet;
    NSScanner *theScanner;
    NSMutableString *jsonText = [[NSMutableString alloc] init];
    NSString *TITLE = @""title": "";
    NSString *postTitle;
    commaSet = [NSCharacterSet characterSetWithCharactersInString:@"""];
    theScanner = [NSScanner scannerWithString:jsonText];
    [jsonText appendString:[NSString stringWithContentsOfURL:redditURL encoding:NSASCIIStringEncoding error:&error]];
    if ([theScanner scanString:TITLE intoString:NULL] && [theScanner scanUpToCharactersFromSet:commaSet intoString:&postTitle] && [theScanner scanString:@""" intoString:NULL]) {
             NSLog(@"%@", postTitle);
    }
}

哦,所有这些构建都没有错误,但这并不奇怪。

非常感谢你的帮助,所有的提示,更正,或任何其他非常感谢。

NSScanner是错误的作业工具。您最好使用JSON(反)序列化程序,例如NSJSONSerialization

为了让您的生活更加轻松,您可以利用AFNetworking,这是一个支持JSON请求的网络框架。你的代码会减少到类似的东西

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://www.reddit.com/r/pics/new/.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSArray *entries = responseObject[@"data"][@"children"];
    for (NSDictionary *entry in entries) {
        NSLog(@"%@", entry[@"title"]);
    }
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

最新更新