Search code examples
objective-cnsjsonserialization

iOS to parse JSON?


I am getting the following response from server

[{"id":"16","name":"Bob","age":"37"},{"id":"17","name":"rob","age":"28"}];

I am using AFNetworking framework for it,

I am getting the above response in NSData and then using the the below code, I am able to collect the data in NSDictionary

NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:&error];

But how to parse the "name" and "age" value from that NSDictionary?


Solution

  • You expected NSDictionary but your response gives you array of dictionaries, try this:

    NSArray *array = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:&error];
    for (NSDictionary *dict in array)
    {
        NSLog(@"Name: %@, age: %@", dict[@"name"], dict[@"age"]);
    }
    

    //Extended

    From the comment below it looks like you have a string from the response, not NSArray as you show in the code above. You can parse string to get the data you want or you can convert it back to the json and NSArray:

        NSString * jsonString = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:&error];
        NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
        NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
       //As I post above
    

    Now you should have an NSArray and my code should do the job.