首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >解析YouTube JSON

解析YouTube JSON
EN

Stack Overflow用户
提问于 2014-06-11 20:48:38
回答 1查看 725关注 0票数 0

我很难从YouTube解析JSON。我试图得到标题,videoId,和默认缩略图网址。我以前分析过JSON,但是我很难从这里得到我想要的东西。

这是我的密码。它与NSDictionary* snippet = [item objectForKey:@"snippet"];上一个无法识别的选择器错误崩溃,错误是-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x108781b0

代码语言:javascript
运行
复制
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define storeURL [NSURL URLWithString: @"https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=25&playlistId=UUkfYL7q5G8CYtZgtSAwmwzw&key=AIzaSyBS4do208_KPGHAhszfVkHadSvtfSgr7Mo"]

#import "KFBYoutubeVideosTableViewController.h"
#import "SVProgressHUD.h"
#import "Reachability.h"
#import "TSMessage.h"
#import "TSMessageView.h"

@interface KFBYoutubeVideosTableViewController ()

@end

@implementation KFBYoutubeVideosTableViewController
@synthesize title, videoID, thumbURL, url, titleArray, videoIDArray, thumbArray;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[SVProgressHUD appearance]setHudBackgroundColor:[UIColor blackColor]];
    [[SVProgressHUD appearance]setHudForegroundColor:[UIColor whiteColor]];
    [SVProgressHUD showWithStatus:@"Loading"];

    Reachability *networkReachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];

    if(networkStatus == NotReachable)
    {
        [TSMessage showNotificationWithTitle:@"Network Error" subtitle:@"No active network connection!" type:TSMessageNotificationTypeError];
        [SVProgressHUD dismiss];
    }

    self.title = @"KFB Videos";

    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [UIColor darkGrayColor];

    url = [NSURL URLWithString:@"https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=25&playlistId=UUkfYL7q5G8CYtZgtSAwmwzw&key=AIzaSyBS4do208_KPGHAhszfVkHadSvtfSgr7Mo"];

    dispatch_async(kBgQueue, ^{
        NSData *data = [NSData dataWithContentsOfURL:url];
        if (data == nil)
        {
            NSLog(@"data is nil");
        }
        else
        {
            [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
        }
    });
}

- (void)viewDidDisappear:(BOOL)animated
{
    [SVProgressHUD dismiss];
}

- (void)fetchedData:(NSData *)responseData
{
    NSError *error;
    titleArray = [[NSMutableArray alloc]init];
    videoIDArray = [[NSMutableArray alloc]init];
    thumbArray = [[NSMutableArray alloc]init];

    NSArray *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
    NSLog(@"%@", json);

    for (NSDictionary *item in json)
    {
        NSDictionary* snippet = [item objectForKey:@"snippet"];
        title = [snippet objectForKey:@"title"];
        videoID = [[snippet objectForKey:@"resourceId"] objectForKey:@"videoID"];
        thumbURL = [[[snippet objectForKey:@"thumbnails"] objectForKey:@"default"] objectForKey:@"url"];

        [titleArray addObject:title];
        [videoIDArray addObject:videoID];
        [thumbArray addObject:thumbURL];
    }

    [self.tableView reloadData];
    [SVProgressHUD dismiss];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [titleArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"];
        cell.textLabel.font = [UIFont systemFontOfSize:16.0];
    }
    if (cell)
    {
        cell.backgroundColor = [UIColor clearColor];
        cell.textLabel.text = [titleArray objectAtIndex:indexPath.row];
        cell.textLabel.textColor = [UIColor blackColor];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{ 
    NSLog(@"Title: %@, Video ID: %@, Thumbnail URL: %@", [titleArray objectAtIndex:indexPath.row],[videoIDArray objectAtIndex:indexPath.row], [thumbArray objectAtIndex:indexPath.row]);

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

下面是JSON:

代码语言:javascript
运行
复制
{
    etag = "\"bvxF-DWHx1toJotsdJBeCm43SLs/tyIRY5zDT7R6YEirBFeFh0tVLCw\"";
    items =     (
                {
            etag = "\"bvxF-DWHx1toJotsdJBeCm43SLs/ON_wGC8nyy0H_bqRqQHlA7mXiM0\"";
            id = UUstIg9nSlWxTaKpWq7G0sppJf9oH5NaDE;
            kind = "youtube#playlistItem";
            snippet =             {
                channelId = UCkfYL7q5G8CYtZgtSAwmwzw;
                channelTitle = "Kentucky Farm Bureau";
                description = "Celebrate June as National Dairy Month with a visit to Jericho Acres Dairy Farm in Henry County.";
                playlistId = UUkfYL7q5G8CYtZgtSAwmwzw;
                position = 0;
                publishedAt = "2014-05-22T12:28:03.000Z";
                resourceId =                 {
                    kind = "youtube#video";
                    videoId = VSCr40jERks;
                };
                thumbnails =                 {
                    default =                     {
                        height = 90;
                        url = "https://i1.ytimg.com/vi/VSCr40jERks/default.jpg";
                        width = 120;
                    };
                    high =                     {
                        height = 360;
                        url = "https://i1.ytimg.com/vi/VSCr40jERks/hqdefault.jpg";
                        width = 480;
                    };
                    maxres =                     {
                        height = 720;
                        url = "https://i1.ytimg.com/vi/VSCr40jERks/maxresdefault.jpg";
                        width = 1280;
                    };
                    medium =                     {
                        height = 180;
                        url = "https://i1.ytimg.com/vi/VSCr40jERks/mqdefault.jpg";
                        width = 320;
                    };
                    standard =                     {
                        height = 480;
                        url = "https://i1.ytimg.com/vi/VSCr40jERks/sddefault.jpg";
                        width = 640;
                    };
                };
                title = "Kentucky Farm Bureau Reports June 2014";
            };
        },
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-06-11 20:56:04

如果仔细观察,标题并不在json响应的底部。所有这些节点都是字典。因此,要从代码中获得您想要的东西,您必须执行以下操作:

代码语言:javascript
运行
复制
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray *items = [json objectForKey:@"items"];
for (NSDictionary *item in json)
{
    NSDictionary* snippet = [item objectForKey:@"snippet"];
    title = [snippet objectForKey:@"title"];
    videoID = [[snippet objectForKey:@"resourceId"] objectForKey:@"videoId"];
    thumbURL = [[[snippet objectForKey:@"thumbnails"] objectForKey:@"default"] objectForKey:@"url"];
}

如果您计划对这些数据做更多的事情,我建议您在创建每个对象时创建对象并解析json。这样你就可以在将来跟踪其他的财产了。这里比这边干净多了。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24172310

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档