Rivten
Rivten

Reputation: 43

Formatting JSON data in NSDictionnary

I am trying to read from a JSON input and put it in a NSDictionnary so as to treat it as smoothly as possible.

The example I'm working on is :

{"count": 4, "next": null, "previous": null, "results": [{"id": 1, "name": "Max"}, {"id": 2, "name": "Hugo"}, {"id": 3, "name": "Romain"}, {"id": 4, "name": "Laurent"}]}

The only thing I'm interested in is the "results" part.

This is how I put the datas in an array :

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"xxxxxx.com/?format=json"]]; 

NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSError* err = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:&err];

The structure of jsonArray

NSArray

https://i.sstatic.net/OFRY3.png

I'm confused at the key/value pairs and I did some researchs without finding anything valuable. What I tried was :

NSArray *values = [[jsonArray objectAtIndex:0] objectAtIndex:1];
    for(NSDictionary *item in values) {
        NSLog( @"%@ --- %@", item[@"id"], item[@"name"]);

But I obviously get an error since the format is not good. I'm new at Objective C and I still searching for the web to find the appropriate answer but help would be much appreciated.

Thank you very much !

Upvotes: 0

Views: 32

Answers (1)

Binary Pulsar
Binary Pulsar

Reputation: 1209

Looks like your JSON is a dictionary containing an array:

NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:&err];

// then get your array
NSArray *results = jsonDict[@"results"];
// then print
for (NSDictionary *dict in results) {
    NSLog(@"id: %@, name: %@", dict[@"id"], dict[@"name"]);
}

Upvotes: 1

Related Questions