开发者

Objective-C SBJSON: order of json array

开发者 https://www.devze.com 2023-01-17 10:57 出处:网络
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 preser

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!


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消