如何收集使用NSDictionary嵌套在数组中的JSON数据

我有以下JSON:

{ 0: 200, error: false, campaigns: { current_campaigns: [ { id: "1150", campaign_type_id: "1", campaign_type: "Type", title: "Name (with type) ", url: "http://www.example.com", special: null, campaign_instructions: "Here's what you do", pay_description: "", start: "2013-10-14 00:00:00", end: "2014-03-31 23:59:59" }, { id: "1151", campaign_type_id: "1", campaign_type: "Type", title: "Name (with type) ", url: "http://www.example.com", special: null, campaign_instructions: "Here's what you do", pay_description: "", start: "2013-10-14 00:00:00", end: "2014-03-31 23:59:59" }, ], new_campaigns: [ { id: "1152", campaign_type_id: "1", campaign_type: "Type", title: "Name (with type) ", url: "http://www.example.com", special: null, campaign_instructions: "Here's what you do", pay_description: "", start: "2013-10-14 00:00:00", end: "2014-03-31 23:59:59" } ] } 

和下面的代码

 NSURL *theJSON = [NSURL URLWithString:@"http://somejsonurl"]; NSURLRequest *request = [NSURLRequest requestWithURL:theJSON]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){ NSError *errorJson = nil; NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&errorJson]; NSArray *campaigns = dataDictionary[@"campaigns"]; for (NSDictionary *campaignList in campaigns) { NSLog(@"Call gave: %@", campaigns); } 

我将如何结束loggingcurrent_campaign标题? 我试过了

  NSLog(@"%@", [campaignList objectForKey:@"title"]); NSLog(@"%@", campaigns[@"title"] ); 

并没有成功。 我在Objective C中是相当新的,并且无法理解如何使用NSArray和NSDictionary挖掘JSON。 任何帮助将不胜感激!

关于JSON最简单的事情是每次看到一个括号“[”,这意味着一个Array的开始,“]”是结束。 每当你看到一个大括号“{”,这意味着一个Dictionary的开始和“}”是结束。

因此,在您的示例中, campaigns是包含Dictionary数组的另一个Dictionarycurrent_campaigns )的Dictionary元素。 这些Dictionaries中的每一个都有一个叫做titlekey

所以长版(未经testing):

 NSDictionary *campaigns = [dataDictionary objectForKey:@"campaigns"]; NSArray *currentCampaigns = [campaigns objectForKey:@"current_campaigns"]; for (NSDictionary *thisCampaign in currentCampaigns) { NSLog(@"title: %@", [thisCampaign objectForKey:@"title"]); }