从NSDictionary获取价值不起作用

时间:2014-02-10 03:49:48

标签: ios objective-c nsdictionary

1.我从Web服务获取JSON数据并将其添加到NSDictionary

NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];

2.然后我在NSLog中显示“dic”现在

{"query": [{"IndexNo": 1,"ID": "01","Picture": "img/food-48.png"}]}

3.然后我从“dic”获取数据值到新的NSDictionary“dt”

NSDictionary *dt = [dic objectForKey: @"query"];

4.然后我在NSLog中显示“dt”现在

({ID = 01;IndexNo = 1;Picture = "img/food-48.png";})

5.我想从“dt”获得“ID”。我用这个代码

NSString *ID = [dt objectForKey: @"ID"];

但是错误

-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x8a40a60

4 个答案:

答案 0 :(得分:1)

你能试试吗

NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
NSArray *arr = [dic objectForKey: @"query"];
NSDictionary *dt = arr[0];
NSString *ID = [dt objectForKey: @"ID"];

答案 1 :(得分:0)

[dic objectForKey: @"query"]实际上返回了一个NSArray。请注意第一个NSLog语句的输出中的这些方括号:

{"query": [...]}

试试这个:

NSArray *dtArray = [dic objectForKey: @"query"];
NSDictionary *dt = dtArray[0];
NSString *ID = [dt objectForKey:@"ID"];

或者使用NSDictionary和NSArray的键值编码行为:

NSString *ID = [[dic valueForKeyPath:@"query.ID"] firstObject];

答案 2 :(得分:0)

NSDictionary *dt = [[dic objectForKey: @"query"] objectAtIndex:0];
NSString *ID = [dt objectForKey: @"ID"];

您正在尝试从数组中获取键的值。改变这些界限。

答案 3 :(得分:0)

来自您的jsonStructure

{"query": [{"IndexNo": 1,"ID": "01","Picture": "img/food-48.png"}]}

键“查询”的对象是一个数组,因为{}是字典而[]是一个数组。以下是

    NSArray *tempArray = [dt objectForKey:@"query"];

    NSDictionary *tempDictionary = [tempArray objectAtIndex:0];
    NSString *ID = [tempDictionary objectForKey:@"ID"];

希望这有帮助。