我试图理解我在使用sbjson解析调用Twitter的GET趋势返回的以下json时出现的问题/:woeid
我使用以下网址:@“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
}
]
}
]
以下是我用于解析和显示名称和网址的代码:
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趋势调用,现在已弃用。该代码仅在我手动删除第一个'['和last']'时才有效。但是,如果我不从响应中删除这些字符,解析器将返回一个 NSString元素的NSArray:json响应。
我应该如何正确解析此响应。提前谢谢。
答案 0 :(得分: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];
}