JSON の解析に問題があります。URL にアクセスすると、次のような JSON 応答が返されます。
//JSON 1
{ "data":
{"array":
["3",
{"array":
[
{"id":"1","message":"Hello","sender":"inot"},
{"id":"2","message":"World","sender":"inot"},
{"id":"3","message":"Hi","sender":"marza"}
]
}
]
},
"message":"MSG0001:Success",
"status":"OK"
}
しかし、data の結果が 1 の場合、JSON 応答は次のようになります。
//JSON 2
{ "data":
{"array":
["3",
{"array":
{"id":"3","message":"Hi","sender":"marza"}
}
]
},
"message":"MSG0001:Success",
"status":"OK"
}
ID、メッセージ、および送信者の値を取得するためにこのコードを実装し、JSON 1 では正常に動作しますが、JSON 2 ではエラーになります。JSON フレームワークを使用します。問題は、JSON 応答がオブジェクト ({ }) または配列 ([ ]) であることを検出する方法です??
// Parse the string into JSON
NSDictionary *json = [myString JSONValue];
// Get all object
NSArray *items = [json valueForKeyPath:@"data.array"];
NSArray *array1 = [[items objectAtIndex:1] objectForKey:@"array"];
NSEnumerator *enumerator = [array1 objectEnumerator];
NSDictionary* item;
while (item = (NSDictionary*)[enumerator nextObject]) {
NSLog(@"id = %@",[item objectForKey:@"id"]);
NSLog(@"message = %@",[item objectForKey:@"message"]);
NSLog(@"sender = %@",[item objectForKey:@"sender"]);
}