Luciano Nascimento
Luciano Nascimento

Reputation: 2600

Allocate Json Array into NSArray (JSONKit)

How can allocate that jSon response into a NSArray?

jSON:

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

Code:

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

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

}

Upvotes: 2

Views: 906

Answers (1)

Alexander
Alexander

Reputation: 7238

You could get JSON into Objects via Apples built in serializer:

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

So there is no need to use external frameworks IMHO (unlees you need performance and JSONKit is, like they say, really 25-40% faster than NSJSONSerialization.

EDIT

Through your comments I guess this is what you want

- (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"]];
    }

}

Upvotes: 2

Related Questions