Objective-C SBJSON:JSON数组的顺序 [英] Objective-C SBJSON: order of json array

查看:143
本文介绍了Objective-C SBJSON:JSON数组的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个iPhone应用程序,该应用程序从服务器获取json字符串并进行解析.它包含一些数据,例如.一系列评论.但是我注意到,当我像这样解析它时,并不会保留json数组的顺序:

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

    {
   "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!

推荐答案

在您的示例JSON中,没有数组而是一个字典.并且在字典中,根据定义,键不以任何方式排序.因此,您需要更改生成JSON的代码以真正使用数组,或者对Cocoa代码中的keys数组进行排序,也许是这样的:

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

这篇关于Objective-C SBJSON:JSON数组的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆