0

我正在尝试在 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

提前致谢,

缺口

4

2 回答 2

1

由于键的对象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课堂上做一个更简洁的代码。

于 2013-04-15T21:16:43.410 回答
1

您需要将类型 gameItem " NSMutableDictionary" 更改为 " id" 并添加检查 -if ([gameItem isKindOfClass: [NSDictionary Class]])在这种情况下初始化 " obj"

于 2013-04-15T21:23:47.707 回答