我目前正在尝试解析此JSON
[{"id":"1","dish_name":"Pasta & ketchup","category":"main","rating":"5","rating_count":null,"author":"Me","ingredients":"Pasta\nKetchup\nWater","description":"Very good for students\nCheap too!","picture":null,"protein":"7","fat":"11","carbs":"12","calories":"244","developer_lock":"1"},{"id":"2","dish_name":"Pasta & Kødsovs","category":"main","rating":"5","rating_count":null,"author":"Me","ingredients":"Pasta\nKødsovs\nWater","description":"Very good for students\nCheap too!","picture":null,"protein":"7","fat":"11","carbs":"12","calories":"244","developer_lock":"1"}]
但它失败并且崩溃了这段代码
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSError *error = NULL;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
recipes = [[NSArray alloc] initWithArray:[json objectForKey:@"dish_name"]];
[uit reloadData];
}
有人有任何线索,为什么它会因错误-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x8077240
而崩溃?
提前致谢。
答案 0 :(得分:2)
以[__NSCFArray objectForKey:]
开头的错误消息表示您有一个NSArray(JSON的根对象是一个数组 - 注意开始和结束方括号),并且您试图将其视为字典。总而言之,
recipes = [[NSArray alloc] initWithObject:[json objectForKey:@"dish_name"]];
应该是
recipes = [[NSArray alloc] initWithObject:[[json objectAtIndex:0] objectForKey:@"dish_name"]];
请注意,数组中有两个对象,因此您可能也想使用[json objectAtIndex:1]
。
编辑:如果你有动态的食谱数量,你可以这样做:
recipes = [[NSMutableArray alloc] init];
for (NSDictionary *dict in json) {
[recipes addObject:[dict objectForKey:@"dish_name"]];
}
答案 1 :(得分:1)
如果您的json
NSDictionary是真实的&有效的NSDictionary对象,您对此的调用:
[json objectForKey:@"dish_name"]
应该正确地返回:
"Pasta & ketchup"
肯定不是数组。它是一个NSString对象。
这就是为什么对“initWithArray
”的召唤是轰炸的原因。