【问题标题】:Trying to parse twitter trends试图解析推特趋势
【发布时间】:2010-12-21 10:56:52
【问题描述】:

我正在尝试解析 Twitter 趋势,但在“as_of”处不断收到解析器错误。有人知道为什么会这样吗?

编辑:

这是我正在使用的代码

NSMutableArray *tweets;
tweets = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:@"http://search.twitter.com/trends/current.json"];
trendsArray = [[NSMutableArray alloc] initWithArray:[CCJSONParser objectFromJSON:[NSString stringWithContentsOfURL:url encoding:4 error:nil]]]; 

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

for (int i = 0; i < [trendsArray count]; i++) {
    dict = [[NSMutableDictionary alloc] init];
    //[post setObject: [[currentArray objectAtIndex:i] objectForKey:@"query"]];
    [dict setObject:[trendsArray objectAtIndex:i] forKey:@"trends"];
    //[dict setObject:[trendsArray objectAtIndex:i] forKey:@"query"];
    //[post setObject:[trendsArray objectAtIndex:i] forKey:@"as_of"];
    [tweets addObject:dict];
    //post = nil;
}

【问题讨论】:

  • 你能发布一些示例代码和数据吗?
  • 你只是在使用search.twitter.com/trends/current.json吗?您使用的是什么 JSON 解析库/框架?发布您正在使用的代码。
  • 我正在使用 CCJSON 来解析趋势 上面发布了代码

标签: iphone objective-c json twitter


【解决方案1】:

我不完全确定您的问题可能是什么,但我已经使用了 twitter api 和 CCJSON,并且得到了一些似乎可以工作的示例代码。如果您将其剪切并粘贴到新项目的 applicationDidFinishLaunching 方法中并包含 CCJSON 文件,它将正常工作(希望如此)。

此代码将从 twitter 获取趋势 json,输出 as_of 值并创建趋势数组。

// Make an array to hold our trends
NSMutableArray *trends = [[NSMutableArray alloc] initWithCapacity:10];

// Get the response from the server and parse the json
NSURL *url = [NSURL URLWithString:@"http://search.twitter.com/trends/current.json"];
NSString *responseString = [NSString stringWithContentsOfURL:url encoding:4 error:nil];
NSDictionary *trendsObject = (NSDictionary *)[CCJSONParser objectFromJSON:responseString]; 

// Output the as_of value
NSLog(@"%@", [trendsObject objectForKey:@"as_of"]);

// We also have a list of trends (by date it seems, looking at the json)
NSDictionary *trendsList = [trendsObject objectForKey:@"trends"];

// For each date in this list
for (id key in trendsList) {
    // Get the trends on this date
    NSDictionary *trendsForDate = [trendsList objectForKey:key];

    // For each trend in this date, add it to the trends array
    for (NSDictionary *trendObject in trendsForDate) {
        NSString *name = [trendObject objectForKey:@"name"];
        NSString *query = [trendObject objectForKey:@"query"]; 
        [trends addObject:[NSArray arrayWithObjects:name, query, nil]];
    }
}

// At the point, we have an array called 'trends' which contains all the trends and their queries.
// Lets see it . . .
for (NSArray *array in trends)
    NSLog(@"name: '%@' query: '%@'", [array objectAtIndex:0], [array objectAtIndex:1]);

希望对你有用,有问题可以留言,

山姆

PS 我使用this site 来可视化 JSON 响应 - 它使查看正在发生的事情变得更加容易 - 我只是将来自 twitter 的 JSON 剪切并粘贴到其中 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 2018-03-27
    • 2013-04-12
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    相关资源
    最近更新 更多