次のステートメントは正しいですか、それとも何か不足していますか?
の戻りオブジェクトをチェックしてNSJSONSerialization
、それが辞書か配列かを確認する必要があります-次のことができます
data = {"name":"joe", "age":"young"}
// NSJSONSerialization returns a dictionary
と
data = {{"name":"joe", "age":"young"},
{"name":"fred", "age":"not so young"}}
// returns an array
各タイプには異なるアクセス方法があり、間違った方法で使用すると壊れます。例えば:
NSMutableArray *jsonObject = [json objectAtIndex:i];
// will break if json is a dictionary
だからあなたは次のようなことをしなければなりません-
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers error:&error];
if ([jsonObjects isKindOfClass:[NSArray class]])
NSLog(@"yes we got an Array"); // cycle thru the array elements
else if ([jsonObjects isKindOfClass:[NSDictionary class]])
NSLog(@"yes we got an dictionary"); // cycle thru the dictionary elements
else
NSLog(@"neither array nor dictionary!");
スタック オーバーフローや Apple のドキュメントなどをよく調べましたが、上記の直接的な確認は見つかりませんでした。