目前我正在使用以下代码来解析发送的 JSON 链接。这也是我为即将推出的 iPhone 应用程序向 Google Reader API 发送 GET 调用的方式。
- (NSArray *)subscriptionList
{
if(!cookies && [cookies count] == 0) {
[self requestSession];
}
NSString * url = @"http://www.google.com/reader/api/0/subscription/list?output=json&client=scroll";
ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
[request setRequestMethod:@"GET"];
[request setRequestCookies:cookies];
[request addRequestHeader:@"Authorization" value:[NSString stringWithFormat:@"GoogleLogin auth=%@", [self auth]]];
[request startSynchronous];
subfeeds = [NSMutableArray array];
// Create new SBJSON parser object
SBJSON *parser = [[SBJSON alloc] init];
if ([request responseStatusCode] == 200) {
NSData * sixty = [request responseData];
NSString * body = [[NSString alloc] initWithData:sixty encoding:NSUTF8StringEncoding];
if (body) {
NSArray *feeds = [parser objectWithString:body error:nil];
NSLog(@"Array Contents: %@", [feeds valueForKey:@"subscriptions"]);
NSLog(@"Array Count: %d", [feeds count]);
NSDictionary *results = [body JSONValue];
NSArray *ohhai = [results valueForKey:@"subscriptions"];
for (NSDictionary *title in ohhai) {
subTitles = [title objectForKey:@"title"];
NSLog(@"title is: %@",subTitles);
}
}
}
return subfeeds;
[subTitles release];
[parser release];
}
我可以使用上面的代码成功解析 JSON,并将标题成功输出到 NSLog。在我的 RootViewController.m 中,我调用以下命令来获取这个 -(NSArray *)subscriptionList。
-(void)viewDidAppear:animated {
GoogleReader * reader = [[GoogleReader alloc] init];
[reader setEmail:gUserString];
[reader setPassword:gPassString];
//feedItems is a NSArray where we store the subscriptionList NSArray
feedItems = [reader subscriptionList];
//NSString *feedTitle = [];
NSLog(@"%@", feedItems);
[reader release];
// the rest of the function
}
上面的代码成功地使用输入的凭据。如您所见,还有一个名为 feedTitle 的注释 NSString。这是我想从解析的 JSON 中提取 @"title" 但我不知道如何调用它的地方。
任何帮助将不胜感激!
这是 JSON 源代码的样子:
{"subscriptions":
[
{"id":"","title":"","categories":[],"sortid":"","firstitemmsec":""},
{"id":"","title":"","categories":[],"sortid":"","firstitemmsec":""},
{"id":"","title":"","categories":[],"sortid":"","firstitemmsec":""},
{"id":"","title":"","categories":[],"sortid":"","firstitemmsec":""},
{"id":"","title":"","categories":[],"sortid":"","firstitemmsec":""}
]
}
我只对“标题”节点感兴趣。