0

次のコードを使用して辞書の内容にアクセスしようとしていますが、何らかの理由で機能しません。

NSLog(@"self.userCommentsArray %@",self.userCommentsArray); nullを 返します

これを手伝ってくれてありがとう。

NSData *jsonData = [NSData dataWithContentsOfURL:myURL];
NSDictionary *userCommentsDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];

    NSLog(@"userCommentsDictionary %@",userCommentsDictionary); // this works

    self.userCommentsArray = [[userCommentsDictionary objectForKey:@"from"] objectForKey:@"name"];

    NSLog(@"self.userCommentsArray %@",self.userCommentsArray); 

辞書の nslog 出力は次のとおりです。

userCommentsDictionary {
        data =     (
                    {
                created = "2013-07-16T18:42:56+02:00";
                from =             {
                    id = 27;
                    name = "user-4";
                };
                id = 2553;
                message = "liquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum";
            },
                    {
                created = "2013-07-16T18:42:56+02:00";
                from =             {
                    id = 28;
                    name = "user-5";
                };
                id = 2554;
                message = "x ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum";
            },
                    {
                created = "2013-07-19T16:18:56+02:00";
                from =             {
                    id = 24;
                    name = "user-1";
                };
                id = 5125;
                message = test comment;
            },
                    {
                created = "2013-07-19T17:00:21+02:00";
                from =             {
                    id = 24;
                    name = "user-1";
                };
                id = 5126;
                message = "test comment ";
       }
        );
        meta =     {
            totalCount = 18;
        };
    }
4

3 に答える 3

0

@"data"json 応答のルートであるキーがありません。すべての名前を取得したいので、このようなことができます。

NSArray *data = userCommentsDictionary[@"data"];
// data array is an array of dicionaries

NSArray *from = [data valueForKey:@"from"];
//from array will fetch all "from" dictionaries 

NSArray *names = [from valueForKey:@"name"];
// names array will contain all names
于 2013-08-04T19:04:39.617 に答える
-1

あるインデックスで配列からオブジェクトにアクセスする必要があり、そこから名前フィールドを選択できると思います。例えば:

self.userCommentsArray =  [userCommentsDictionary objectForKey:@"data"];
id someObject  = [self.userCommentArray objectAtIndex:0] // or some other index
NSString *name = [someObject valueForKey:@"name"];
于 2013-08-04T19:10:20.433 に答える