在IOS中解析嵌套的JSON代码

时间:2013-04-15 20:28:24

标签: ios json parsing nsarray nsmutabledictionary

我正在尝试解析iOS中的以下JSON代码。 JSON代码由一系列编号为0到x的游戏组成。我一直在寻找,但似乎无法找到任何以这种格式拥有JSON的例子。

{
"command":"show_my_games",
"0":{"gameid":"7","foruserid":"16","againstuserid":"0","casefor":"","caseagainst":"","status":"0","argumentid":"7","againstusername":null,"forusername":"Gem","argument":"argument 1"},
"1":{"gameid":"8","foruserid":"15","againstuserid":"16","casefor":"","caseagainst":"","status":"0","argumentid":"23","againstusername":"Gem","forusername":"Nick","argument":"argument 2"},
"2":{"gameid":"9","foruserid":"18","againstuserid":"16","casefor":"","caseagainst":"","status":"0","argumentid":"26","againstusername":"Gem","forusername":"Nick","argument":"argument 3"}
}

我已经创建了一个游戏对象,对于JSON数组中的每个项目,我想创建一个新的游戏对象,并将其添加到游戏数组中。我在解析JSON时遇到问题,我很感激任何帮助或建议。

我正在尝试使用的代码是

            NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&err];

            for (NSMutableDictionary * gameItem in json) {
                Game *obj = [Game new];
                obj.GameID=[gameItem objectForKey:@"gameid"];
                obj.Argument=[gameItem objectForKey:@"argument"];
                obj.CaseFor=[gameItem objectForKey:@"casefor"];
                obj.CaseAgainst=[gameItem objectForKey:@"caseagainst"];
                obj.CaseForOwner=[gameItem objectForKey:@"forusername"];
                obj.CaseAgainstOwner=[gameItem objectForKey:@"againstusername"];
                obj.CaseForOwnerID=[gameItem objectForKey:@"foruserid"];
                obj.CaseAgainstOwnerID=[gameItem objectForKey:@"againstuserid"];
                //add to the players game array
                [myGameArray addObject:obj];

            }
            NSLog(@"array: %@", myGameArray);

当我尝试从JSON数组中提取数据时,收到以下错误。 - [__ NSCFString objectForKey:]:无法识别的选择器发送到实例0x1f06f4e0

提前致谢,

尼克

2 个答案:

答案 0 :(得分:2)

代码正在破碎,因为密钥command的对象不是字典。

您可以像这样修改代码。

    for (NSString *key in json){
        id object = json[key];
        if ([object isKindOfClass:[NSDictionary class]]) {
           Game *obj = [Game new];
           obj.GameID=[gameItem objectForKey:@"gameid"];
           obj.Argument=[gameItem objectForKey:@"argument"];
           obj.CaseFor=[gameItem objectForKey:@"casefor"];
           obj.CaseAgainst=[gameItem objectForKey:@"caseagainst"];
           obj.CaseForOwner=[gameItem objectForKey:@"forusername"];
           obj.CaseAgainstOwner=[gameItem objectForKey:@"againstusername"];
           obj.CaseForOwnerID=[gameItem objectForKey:@"foruserid"];
           obj.CaseAgainstOwnerID=[gameItem objectForKey:@"againstuserid"];
           //add to the players game array
          [myGameArray addObject:obj];
    }

我建议您在initWithDictionary:(NSDictionary *)dictionary课程中设置Game以获得更清晰的代码。

答案 1 :(得分:1)

您需要将gameItem类型“NSMutableDictionary”更改为“id”并添加检查 - if ([gameItem isKindOfClass: [NSDictionary Class]]),如果是这种情况,请初始化“obj