0

I'm trying to figure out how to populate a table from a JSON array. So far, I can populate my table cells perfectly fine by using the following code:

self.countries = [[NSArray alloc]initWithObjects:@"Argentina",@"China",@"Russia",nil];

Concerning the JSON, I can successfully retrieve one line of text at a time and display it in a label. My goal is to populate an entire table view from a JSON array. I tried using the following code, but it still won't populate my table. Obviously I'm doing something wrong, but I searched everywhere and still can't figure it out:

NSURL *url = [NSURL URLWithString:@"http://BlahBlahBlah.com/CountryList"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
    NSLog(@"%@",[JSON objectForKey:@"COUNTRIES"]);
    self.countries = [JSON objectForKey:@"COUNTRIES"];
}
failure:nil];
[operation start];

I am positive that the data is being retrieved, because the NSLog outputs the text perfectly fine. But when I try setting my array equal to the JSON array, nothing happens. I know the code is probably wrong, but I think I'm on the right track. Your help would be much appreciated.

EDIT: This is the text in the JSON file I'm using:

{
 "COUNTRIES": ["Argentina", "China", "Russia",]
}           

-Miles

4

1 回答 1

1

It seems that you need some basic JSON parsing. If you only target iOS 5.0 and above devices, then you should use NSJSONSerialization. If you need to support earlier iOS versions, then I really recommend the open source JSONKit framework.

Having recommended the above, I myself almost always use the Sensible TableView framework to fetch all data from my web service and automatically display it on a table view. Saves me a ton of manual labor and makes app maintenance a breeze, so it's probably something to consider too. Good luck!

于 2013-03-30T21:42:27.907 回答