JSON数据以错误的顺序添加到NSArray中

时间:2012-11-25 23:57:05

标签: objective-c json nsarray

我正在向NSArray添加键值字符串,但它们的添加顺序错误,这让我相信这是做错的方法 -

我的json采用以下格式:

[{
    "story1":
        {data in here}
    "story2":
                {data in here}....

并且在我的代码中我希望在NSArray中获取story1和story2(以及更多)的字符串值,我实现但是它们的顺序相反 - story2,story1:

NSArray *jsonArr = [NSJSONSerialization JSONObjectWithData:theData options:kNilOptions error:&error];

for (NSString *pItem in [jsonArr objectAtIndex:0]) {
  NSLog(@"Product: %@", pItem);
}

有更好的方法可以做到这一点,如果没有,我该如何反转数组?

2 个答案:

答案 0 :(得分:1)

// Instead Normal NSArray user NSOrderedSet which preserves the order of objects
NSOrderedSet *orderSet = [NSOrderedSet orderedSetWithArray:jsonArr];

// Access your value From NSOrderedSet same as NSArray
NSDictionary *dict = [orderSet objectAtIndex:0];
NSLog(@"%@",dict);

答案 1 :(得分:1)

您的JSON在JSON数组中定义了一个JSON对象。当你反序列化它时,你得到的NSArray包含一个NSDictionary,而NSDictionary又包含键值对,但是NSDictionary没有定义键的排序(JSON对象也没有)。即。

{ "story1" : "foo", "story2" : "bar" }

{ "story2" : "bar", "story1" : "foo" }

是对同一物体的重复。

如果您需要订购,则需要重新构建JSON数据。接下来会做的伎俩

[
    { "story1" : { ... } },
    { "story2" : { ... } }
]

或者,当您访问对象中的数据时,可以先对键进行排序。使用您的示例:

NSArray *jsonArr = [NSJSONSerialization JSONObjectWithData:theData ...];
NSDictionary *jsonDictionary = [jsonArr objectAtIndex: 0];

NSArray* sortedKeys = [[jsonDictionary allKeys] sortedArrayUsingComparator: (^NSComparator)(id obj1, id obj2) { /* a comparator */ }];
for (NSString *key in [sortedKeys]) 
{
    NSLog(@"Product: %@", [jsonDictionary objectForKey: key]);
}