我正在使用新的 ios5“NSJSONSerialization”功能从网站获取一些技术新闻。我似乎一切正常,直到我尝试将 NSDictionary 解析为 NSArray。我在这里包含了代码。第一个控制台测试(测试 1)运行良好 - 我得到一个充满返回 json 数据的控制台。但是在第二个控制台测试(测试 2 - 检查 nsarray 内容的那个)中,给出了以下消息:“返回数组:(null)”。有任何想法吗?可能是因为我重用了错误变量吗?我难住了。
这是代码:
// create the string for making the api call to the website
NSString* theURL = [NSString stringWithFormat:@"http://pipes.yahoo.com/pipes/pipe.run?_id=9DfJELfJ2xGnjAQWJphxuA&_render=json"];
// declare and assign variables necessary to generate the actual url request
NSError* err = nil;
NSURLResponse* response = nil;
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
NSURL* URL = [NSURL URLWithString:theURL];
[request setURL:URL];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setTimeoutInterval:30];
// make the actual url request - get the data from yahoo pipes, in json format
NSData* jsonData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
// assign the entire result to a dictionary
NSDictionary *resultsDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&err];
//*** test 1: use the console to test results:
NSLog(@"NSDictionary returned: %@",resultsDictionary);
// parse the whole returned list of items (in dictionary form) into a large array
NSArray* arrayOfReturnedItems = [resultsDictionary objectForKey:@"items"];
//*** test 2: view the items returned (in the console)
NSLog(@"Array returned: %@",[arrayOfReturnedItems objectAtIndex:0]);