我有以下 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);
}
我将如何最终记录 current_campaign 标题? 我试过了
NSLog(@"%@", [campaignList objectForKey:@"title"]);
NSLog(@"%@", campaigns[@"title"] );
并没有成功。我是 Objective C 的新手,无法理解如何使用 NSArray 和 NSDictionary 深入研究 JSON。任何帮助将不胜感激!
最佳答案
关于 JSON
最容易记住的事情是每次你看到括号“[”,这意味着 Array
的开始,而“]”是结束.每次看到大括号“{”时,表示 Dictionary
的开头,而“}”表示结尾。
因此,在您的示例中,campaigns
是一个 Dictionary
元素,其中包含另一个 Dictionary
(current_campaigns
) 字典
的数组
。每个 Dictionaries
都有一个名为 title
的 key
。
所以长版(未经测试):
NSDictionary *campaigns = [dataDictionary objectForKey:@"campaigns"];
NSArray *currentCampaigns = [campaigns objectForKey:@"current_campaigns"];
for (NSDictionary *thisCampaign in currentCampaigns) {
NSLog(@"title: %@", [thisCampaign objectForKey:@"title"]);
}
关于ios - 如何使用 NSDictionary 收集嵌套在数组中的 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22264261/