我有以下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。任何帮助将不胜感激!
答案 0 :(得分:3)
关于JSON
最容易记住的是每次看到括号" [",这意味着Array
和"]的开头#34;结束了。每当你看到一个大括号" {"这意味着Dictionary
和"}"的开头结束了。
因此,在您的示例中,campaigns
是Dictionary
元素,其他Dictionary
(current_campaigns
)包含Array
Dictionaries
。这些Dictionaries
中的每一个都有一个名为key
的{{1}}。
所以长版本(未经测试):
title