[英]Parse nested JSON code in IOS
我正在嘗試在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
提前致謝,
缺口
由於鍵盤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];
}
我建議在Game
類中創建一個initWithDictionary:(NSDictionary *)dictionary
以獲取更簡潔的代碼。
您需要將類型gameItem“ NSMutableDictionary
”更改為“ id
”並添加檢查if ([gameItem isKindOfClass: [NSDictionary Class]])
,在這種情況下,請初始化“ obj
”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.