views:

104

answers:

2

Hi! I have an iPhone application which gets a json string from a server and parses it. It contains some data and, eg. an array of comments. But I've noticed that the order of the json array is not preserved when I parse it like this:

    // parse response as json
SBJSON *jsonParser = [SBJSON new];
NSDictionary *jsonData = [jsonParser objectWithString:jsonResponse error:nil];

NSDictionary* tmpDict = [jsonData objectForKey:@"rows"];
NSLog(@"keys coming!");
NSArray* keys = [tmpDict allKeys];
for (int i = 0;i< [keys count]; i++) {
    NSLog([keys objectAtIndex:i]);
}

Json structure:

{    "pagerInfo":{

      "page":"1",

      "rowsPerPage":15,

      "rowsCount":"100"

   },

   "rows":{

      "18545":{

         "id":"18545",

         "text":"comment 1"

      },

      "22464":{

         "id":"22464",

         "text":"comment 2"

      },

      "21069":{

         "id":"21069",

         "text":"comment 3"

      },

… more items

   }

}

Does anyone know how to deal with this problem? Thank you so much!

A: 

In your example JSON there is no array but a dictionary. And in a dictionary the keys are by definition not ordered in any way. So you either need to change the code that generates the JSON to really use an array or sort the keys array in your Cocoa code, maybe like this:

NSArray *keys = [[tmpDict allKeys] sortedArrayUsingSelector: @selector(compare:)];

Using that sorted keys array you can then create a new array with the objects in the correct order:

NSMutableArray *array = [NSMutableArray arrayWithCapacity: [keys count]];
for (NSString *key in keys) {
    [array addObject: [tmpDict objectForKey: key]];
}
Sven
Thanks, so the ids in that json have to be ordered to solve that problem? Is there any way to parse it so that [arrayAfterSomeGreatFunction objectAtIndex:0] would return the "comment 1" string?
Cocoprogrmr
I edited my answer to show you one possible way to create a new array with the sorted objects.
Sven
A: 

Cocoprogrmr,

Here's what you need to do: after you have parsed out your json string and loaded that into a NSArray (i.e. where you have NSArray* keys written above), from there you could put that into a for loop where you iterate over the values in your keys array. Next, to get your nested values out, for example, to get the values of rows/text, use syntax like the following:

for (NSDictionary *myKey in keys)
{
  NSLog(@"rows/text --> %@",  [[[myKey objectForKey:@"rows"] objectForKey:@"text"]);
}

That should do it. My syntax might not be perfect there, but you get the idea.

Andy

andyengle