简体   繁体   English

Objective-C SBJSON:JSON数组的顺序

[英]Objective-C SBJSON: order of json array

I have an iPhone application which gets a json string from a server and parses it. 我有一个iPhone应用程序,该应用程序从服务器获取json字符串并进行解析。 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: 但是我注意到当我这样解析它时,json数组的顺序并没有保留:

    // 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: Json结构:

    {
   "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. 在您的示例JSON中,没有数组,只有字典。 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: 因此,您需要更改生成JSON的代码以真正使用数组,或者对Cocoa代码中的keys数组进行排序,也许是这样的:

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, Cocoprogrmr,

Here's what you need to do: after you have parsed out your json string and loaded that into a NSArray (ie 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. 这是您需要做的:解析完json字符串并将其加载到NSArray(即上面写有NSArray *键的位置 )之后,可以将其放入for循环中,在其中循环访问其中的值。您的数组。 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 安迪

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM