I am trying to understand an issue I am having when using sbjson to parse the following json returned by a call to Twitter's GET trends/:woeid
I am using the following URL: @"http://api.twitter.com/1/trends/1.json" and I get the following response: (truncated to save space)
[
{
"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
}
]
}
]
Here is the code I'm using to parse and display the name and 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];
This is sample code that is broken because it was targeted to Twitter's GET trends call which is now deprecated. The code will only work if I manually remove the first '[' and last ']'. However if I don't remove those characters from the response, the parser returns a NSArray of one NSString element: the json response.
How should I correctly parse this response. Thanks in advance.