2

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

}
4
  • the line NSArray *jsonData = [responseData objectFromJSONData]; already gets you your JSON into an array. What did you mean by using the verb "allocate" ? Commented Feb 15, 2013 at 7:41
  • @IcanZilb This way it will pick up all city entries or just the first one? Commented Feb 15, 2013 at 7:43
  • Just add "NSLog(@"obj:%@", jsonData)" after that line and you will see. Commented Feb 15, 2013 at 7:45
  • @IcanZilb Its not working, get error. Commented Feb 15, 2013 at 7:58

1 Answer 1

2

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

}

Sign up to request clarification or add additional context in comments.

5 Comments

Using JSONKit how I can do that?
You are sending a json object in an array, so your line NSArray *jsonData = [responseData objectFromJSONData]; is just fine. That's all you need.
With my code the cellsCity return only Entry 3, and using NSArray *jsonData = [responseData objectFromJSONData]; I get error.
I would like cellsCity return an array with Entry 1, Entry 2, Entry 3.
Sure you are getting just entry 3. You are overwriting cellsCity in the loop so that only the last entry (3) will "survive"!!! See my edits

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.