Objective-C SBJSON: order of json array

匿名 (未验证) 提交于 2019-12-03 09:52:54

问题:

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!

回答1:

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


回答2:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!