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