0

我有一个提供 JSON 的 RESTful API。我这样称呼它:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    dispatch_async(kBgQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL: 
                        kProjectList];
        [self performSelectorOnMainThread:@selector(fetchedData:) 
                               withObject:data waitUntilDone:YES];
    });
}

然后我有我的 fetchedData 方法:

- (void)fetchedData:(NSData *)responseData {
    //parse out the json data
    NSError* error;
    NSDictionary* json = [NSJSONSerialization 
                          JSONObjectWithData:responseData //1

                          options:kNilOptions 
                          error:&error];
    //NSArray *projects = [json objectForKey:@"name"]; //2

    NSLog(@"name: %@", json); //3
}

如果我取消注释 //NSArray 行我得到-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x6d81720

随着它被注释掉,我的字典记录:

(
        {
        "created_at" = "2012-04-04T01:46:51Z";
        description = "First Project Created";
        id = 1;
        name = "Test 1";
        "updated_at" = "2012-04-04T01:46:51Z";
    },
        {
        "created_at" = "2012-04-04T01:47:23Z";
        description = "Second Project Created";
        id = 2;
        name = "Test 2";
        "updated_at" = "2012-04-04T01:47:23Z";
    }
)
4

1 回答 1

1

你有一个字典数组,而不是数组字典。代替 objectForKey,使用 objectAtIndex 并分配给字典。做这个:

NSDictionary *projects = [[json objectAtIndex:0] objectForKey:@"name"];
于 2012-04-04T02:52:45.727 回答