2

好的,我得到一个 Json 提要并将其存储到一个名为 jsonArray 的数组中。然后我循环遍历 jsonArray,取出数组键并将它们存储为字符串。然后我将这些字符串添加到一个名为 innerDict 的内部字典中,然后我使用下面的键将该字典添加到 info 字典中。所以基本上innerDict存储在infoDict里面。

-(void)pointInfo{

infoDict = [[NSMutableDictionary alloc]init];

for (int i = 0; i < jsonArray.count; i++) {

innerDict = [[NSMutableDictionary alloc]init];

info = [[jsonArray objectAtIndex:i]objectForKey:@"inf"];
thePostCode = [[jsonArray objectAtIndex:i]objectForKey:@"pc"];
mail = [[jsonArray objectAtIndex:i]objectForKey:@"mail"];
url = [[jsonArray objectAtIndex:i]objectForKey:@"url"];
type = [[jsonArray objectAtIndex:i]objectForKey:@"items"];

[innerDict setObject:type forKey:@"Items"];
[innerDict setObject:info forKey:@"Info"];
[innerDict setObject:mail forKey:@"Mail"];
[innerDict setObject:url forKey:@"Url"];

[infoDict setObject:innerDict forKey:thePostCode];

}

infoDict 的输出如下所示:

infoDict is {
"ME14 4NN" =     {
    Info = "";
    Items = 4;
    Mail = "";
    Url = "";
};
"ME15 6LG" =     {
    Info = af;
    Items = "0,6,9";
    Mail = "";
    Url = "";
};
"ME15 6YE" =     {
    Info = "";
    Items = "4,5,6,7,11";
    Mail = "";
    Url = "";
};
}

现在我要做的是获取 innerDict 对象的值,即上面的“ME15 6YE”,并将其用作查询以提取 Info、Items、Mail 和 Url 键的关联数据。我一直盯着我的屏幕几个小时,但我就是不明白。

I can pull out the last object of the inner dict using the below however I would like to grab all the values associated with a particular postcode which would be the innerDict key. Completely brain fried at the moment!

for (NSMutableDictionary *dictionary in infoDict) {

    NSLog(@"URL %@", [innerDict objectForKey:@"Url"]);
    NSLog(@"MAIL %@", [innerDict objectForKey:@"Mail"]);
    NSLog(@"ITEMS %@", [innerDict objectForKey:@"Items"]);
    NSLog(@"ITEMS %@", [innerDict objectForKey:@"Info"]);

}
4

2 回答 2

1

To get the correct inner dictionary, use objectForKey:

NSDictionary *innerDict = [infoDict objectForKey:@"ME15 6YE"];
NSLog(@"Url %@", [innerDict objectForKey:@"Url"]);
NSLog(@"Mail %@", [innerDict objectForKey:@"Mail"]);
NSLog(@"Items %@", [innerDict objectForKey:@"Items"]);
NSLog(@"Info %@", [innerDict objectForKey:@"Info"]);
于 2013-02-08T14:59:29.497 回答
1

Maybe I'm misunderstanding something, but I think this should answer your questions.

You're using dictionary in the for loop, but trying to access it via innerDict. Change it to:

for (NSMutableDictionary *dictionary in infoDict) {
    NSLog(@"URL %@", [dictionary objectForKey:@"Url"]);
    NSLog(@"MAIL %@", [dictionary objectForKey:@"Mail"]);
    NSLog(@"ITEMS %@", [dictionary objectForKey:@"Items"]);
    NSLog(@"ITEMS %@", [dictionary objectForKey:@"Info"]);
}

Or, for a single one,

NSMutableDictionary *inner = [infoDict objectForKey:@"POST CODE HERE"];
NSLog(@"URL %@", [inner objectForKey:@"Url"]);
NSLog(@"MAIL %@", [inner objectForKey:@"Mail"]);
NSLog(@"ITEMS %@", [inner objectForKey:@"Items"]);
NSLog(@"ITEMS %@", [inner objectForKey:@"Info"]);
于 2013-02-08T15:00:36.853 回答