将Json数组分配到NSArray(JSONKit)

时间:2013-02-15 07:38:35

标签: objective-c xcode

如何将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];
    }

}

1 个答案:

答案 0 :(得分:2)

你可以通过内置在串行器中的苹果将JSON加入对象:

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

所以没有必要使用外部框架恕我直言(unlees你需要性能和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"]];
    }

}