SBJSONparsing与Twitter的GET趋势问题/:woeid

我想了解一个问题,当我使用sbjsonparsing下面的json调用返回的GET GET trends::woeid

我正在使用以下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 } ] } ] 

这里是我用来parsing和显示名称和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趋势调用而被破坏的示例代码,现在已经被弃用了。 该代码将只能手动删除第一个'['和最后']'。 但是,如果我不从响应中删除这些字符,parsing器将返回一个 NSString元素的NSArray:json响应。

我应该如何正确parsing这个回应。 提前致谢。

我自己解决了这个问题,我被NSArray弄糊涂了,只有一个看起来像是一个string的元素。

数组中的一个元素不是一个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]; 

使用苹果提供的新发布的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]; }