在NSDictionary / NSArray从JSON保持KEYS正确的顺序

我有一个从请求返回的JSON数组。
数据是这样的(它来自外部来源,不能从服务器更改):

[{"clients": {"name":"Client name here","telephone":"00000","email":"clientemail@hotmail.com","website":"www.clientname.com"} }] 

我按此顺序收到JSON数组。

我有下面的Objective-C:

 //jsonString is the json string inside type NSString. NSMutableDictionary *tempDict = [jsonString JSONValue]; NSMutableDictionary *clients = [tempDict objectForKey:@"clients"]; for(NSString *key in clients) { id value = [tempDict objectForKey:key]; for(NSString *itemKey in key) { NSLog(@"ITEM KEY %@: ",itemKey); } } 

它打印键的顺序是:
电话
电子邮件
名称
网站

我需要它打印如何收到(例如):
名称
电话
电子邮件
网站

我已经读过字典根据定义未sorting,所以很高兴使用数组而不是字典。

但是我已经看到有关可能的解决scheme(使用keysSortedByValueUsingSelector )StackOverflow上的几个线程:
获取按各自的值sorting的NSDictionary键
我可以根据Objective-C中的键sortingNSDictionary吗?
按字典值将NSDictionary键sorting到NSArray中
我可以根据Objective-C中的键sortingNSDictionary吗?

我已经尝试过他们,并没有得到任何好处。 不知道这是不是我的实现是错误的。

我试过(尝试1):

 NSArray *orderedKeys = [clients keySortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2){ return [obj1 compare:obj2]; }]; for(NSString *key in orderedKeys) { id value = [tempDict objectForKey:key]; for(NSString *keyThree in key) { NSLog(@"API-KEY-ORDER %@: ",keyThree); } } 

接收错误: [__NSArrayM keySortedByValueUsingComparator:]: unrecognized selector sent to instance

也试过(尝试2):

 NSArray *sortedKeys = [[clients allKeys] sortedArrayUsingSelector: @selector(compare:)]; NSMutableArray *sortedValues = [NSMutableArray array]; for (NSString *key in sortedKeys){ [sortedValues addObject: [tempDict objectForKey: key]]; //[sortedValues addObject: [all objectForKey: key]]; //failed } 

但是,即使客户端是一个NSMutableDictionaryselect器上的另一个错误。

 [__NSArrayM allKeys]: unrecognized selector sent to instance 0x4b6beb0 

我在我想我要迭代NSMutableDictionary并手动将它们放入一个新的NSMutableArray正确的顺序。

任何想法将非常感激?
或者anybodies代码片段尝试在我的问题将同样赞赏。

原则上,NSDictionary不仅是无序的,而且JSON对象也是如此。 这些JSON对象是相同的

 [{"clients": {"name":"Client name here","telephone":"00000","email":"clientemail@hotmail.com","website":"www.clientname.com"} }] [{"clients": {"website":"www.clientname.com","name":"Client name here","telephone":"00000","email":"clientemail@hotmail.com"} }] 

如果服务器想要订购密钥,则需要发送一个数组。 当然,你可以使用keysSortedByValueUsingComparator:方法来获得sorting顺序的键。

首先,你看到的exception是因为select器名称不正确。 你应该使用keysSortedByValueUsingComparator 。 其次,你不能对键进行sorting,因为你从服务器获得它们的顺序似乎没有任何特定的顺序。 如果你必须按照这个顺序,然后从服务器发送一个标签(“index”),然后用这个标签进行sorting。