2

如何将该json响应分配到一个NSArray

JSON:

[{"city":"Entry 1"},{"city":"Entry 2"},{"city":"Entry 3"}]

代码:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSArray *jsonData = [responseData objectFromJSONData];

    for (NSDictionary *dict in jsonData) {
        cellsCity = [[NSArray alloc] initWithObjects:[dict objectForKey:@"city"], nil];
    }

}
4

1 回答 1

2

您可以通过 Apple 内置的序列化程序将 JSON 转换为对象:

NSError *error = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:aData options:NSJSONWritingPrettyPrinted error:&error];
if(error){
    NSLog(@"Error parsing json");
    return;
} else {...}

所以没有必要使用外部框架恕我直言(除非你需要性能,而且 JSONKit 就像他们说的那样,真的比 NSJSONSerialization 快 25-40%。

编辑

通过您的评论,我想这就是您想要的

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //First get the array of dictionaries
    NSArray *jsonData = [responseData objectFromJSONData];
    NSMutableArray *cellsCity = [NSMutableArray array];
    //then iterate through each dictionary to extract key-value pairs 
    for (NSDictionary *dict in jsonData) {
        [cellsCity addObject:[dict objectForKey:@"city"]];
    }

}

于 2013-02-15T07:46:39.570 回答