从本地JSON文件获取嵌套数据

时间:2014-08-24 03:49:04

标签: ios objective-c json

现在我有NSDictionary对象JSONDictionary,我如何获取中的嵌套数据?

    NSString *JSONFilePath = [[NSBundle mainBundle] pathForResource:@"sAPI" ofType:@"json"];
    NSData *JSONData = [NSData dataWithContentsOfFile:JSONFilePath];
    NSDictionary *JSONDictionary = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:nil];
    NSLog(@"Dictionary: %@", JSONDictionary);

sAPI.json摘录:

{
    "ss": [{
               "name": "bl",
               },
               "ls": [{
                           "name": "ML",
                           "abbreviation": "ml",
                           "id": 10,

1 个答案:

答案 0 :(得分:1)

由于您要求我在对不同答案的评论中这样做,我将在此处回答。要获得其中一个联赛的name值,请按照

进行操作
NSDictionary *JSONDictionary = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:nil]; //root object
NSArray *sports = JSONDictionary[@"sports"]; //array containing all sports (baseball, football, etc.)
NSDictionary *baseball = sports[0]; //dictionary containing info about baseball
NSArray *baseballLeagues = baseball[@"leagues"]; //array containing all leagues for baseball
NSDictionary *MLB = baseballLeagues[0]; //dictionary for only the MLB league
NSString *MLBName = MLB[@"name"]; //the full name of the MLB

此示例仅适用于MLB,但可以通过查找您想要使用的其他联赛或运动的索引轻松更改。

请注意,本答案中使用的方括号是以下方法的简写

dictionary[@"key"]; -short for-> [dictionary objectForKey:@"key"];
array[0]; -short for-> [array objectAtIndex:0];