0

我试图了解使用 sbjson 解析调用 Twitter 的 GET 趋势/:woeid 返回的以下 json 时遇到的问题

我正在使用以下 URL:@“http://api.twitter.com/1/trends/1.json”,我得到以下响应:(截断以节省空间)

[  
  {  
    "trends": [  
      {  
        "name": "Premios Juventud",  
        "url": "http://search.twitter.com/search?q=Premios+Juventud",  
        "query": "Premios+Juventud"  
      },  
      {  
        "name": "#agoodrelationship",  
        "url": "http://search.twitter.com/search?q=%23agoodrelationship",  
        "query": "%23agoodrelationship"  
      }  
    ],  
    "as_of": "2010-07-15T22:40:45Z",  
    "locations": [  
      {  
        "name": "Worldwide",  
        "woeid": 1  
      }  
    ]  
  }  
]  

这是我用来解析和显示名称和 url 的代码:

NSMutableString *content = [[NSMutableString alloc] initWithBytes:[responseData bytes] length:[responseData length] encoding:NSUTF8StringEncoding];

[content replaceCharactersInRange:NSMakeRange(0, 1) withString:@""];
[content replaceCharactersInRange:NSMakeRange([content length]-1, 1) withString:@""];
NSLog(@"Content is: %@", content);

SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *json = [parser objectWithString:content];


//NSArray *trends = [json objectForKey:@"trends"];
NSArray *trends = [json objectForKey:@"trends"];
for (NSDictionary *trend in trends)
{
    [viewController.names addObject:[trend objectForKey:@"name"]];
    [viewController.urls addObject:[trend objectForKey:@"url"]];
}

[parser release];

这是一个被破坏的示例代码,因为它的目标是 Twitter 的 GET 趋势调用,现在已弃用。仅当我手动删除第一个“[”和最后一个“]”时,该代码才有效。但是,如果我不从响应中删除这些字符,解析器将返回一个NSString 元素的 NSArray:json 响应。

我应该如何正确解析这个响应。提前致谢。

4

1 回答 1

2

我自己解决了这个问题,我对 NSArray 只返回一个似乎是字符串的元素感到困惑。

数组中的一个元素不是 NSString 而是 NSDictionary,一旦我理解了这一点,我就可以通过将元素分配给 NSDictionary 来正确处理数据,然后使用适当的键访问“趋势”数据:

NSMutableString *content = [[NSMutableString alloc] initWithBytes:[responseData bytes] length:[responseData length] encoding:NSUTF8StringEncoding];

SBJsonParser *parser = [[SBJsonParser alloc] init];
NSArray *json = [parser objectWithString:content];

NSDictionary *trends = [json objectAtIndex:0];
for (NSDictionary *trend in [trends objectForKey:@"trends"])
{
    [viewController.names addObject:[trend objectForKey:@"name"]];
    [viewController.urls addObject:[trend objectForKey:@"url"]];
}

[parser release];

使用 Apple 提供的新发布的 NSJSONSerialization 会更简洁一些:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{ 
    NSArray *json = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];    

    NSDictionary *trends = [json objectAtIndex:0];
    for (NSDictionary *trend in [trends objectForKey:@"trends"])
    {
        [viewController.names addObject:[trend objectForKey:@"name"]];
        [viewController.urls addObject:[trend objectForKey:@"url"]];
    }    

    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [viewController.serviceView reloadData];
}
于 2011-11-02T12:03:38.683 回答