7

次のステートメントは正しいですか、それとも何か不足していますか?

の戻りオブジェクトをチェックして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 のドキュメントなどをよく調べましたが、上記の直接的な確認は見つかりませんでした。

4

1 に答える 1

5

これが正しいかどうかを尋ねているだけなら、はい、安全に処理できますjsonObjects。これは、 を返す他の API で行う方法でもありますid

于 2012-10-18T03:47:31.707 に答える