2

我一直在尝试在 IOS5 中按顺序解析我的 JSON。它是从服务器按顺序来的,所以我知道不是那样的。这是我的代码:

NSArray *userData = [update JSONValue];
NSLog(@"USERDATA%@", userData);
NSEnumerator *enumerator = [userData objectEnumerator];
id key;
while (key = [enumerator nextObject]) {
    NSDictionary *value = key;
    NSString *comment = [value objectForKey:@"comment"];
    NSLog(@"USERCOMMENT %@", comment);
}

第一个 NSLog,一切看起来都很漂亮。第二个 NSLog 让我一切都乱了套。我几乎无计可施。

第一个 NSLOG:

USERDATA{
    1 =     {
        comment = "Test 6";
        photoID = 1;
        postedDate = "2 days ago";
        userID = 17;
        userPic = "members/0/image01.png";
        username = kismet;
    };
    2 =     {
        comment = "Test 5";
        photoID = 1;
        postedDate = "2 days ago";
        userID = 17;
        userPic = "members/0/image01.png";
        username = kismet;
    };
    3 =     {
        comment = "Test 4";
        photoID = 1;
        postedDate = "2 days ago";
        userID = 17;
        userPic = "members/0/image01.png";
        username = kismet;
    };
    4 =     {
        comment = "Test 3";
        photoID = 1;
        postedDate = "2 days ago";
        userID = 17;
        userPic = "members/0/image01.png";
        username = kismet;
    };
    5 =     {
        comment = "Test 2";
        photoID = 1;
        postedDate = "2 days ago";
        userID = 17;
        userPic = "members/0/image01.png";
        username = kismet;
    };
    6 =     {
        comment = "Test 1";
        photoID = 1;
        postedDate = "2 days ago";
        userID = 17;
        userPic = "members/0/image01.png";
        username = kismet;
    };
}

第二个NSLog:

USERCOMMENT Test 4
USERCOMMENT Test 6
USERCOMMENT Test 1
USERCOMMENT Test 3
USERCOMMENT Test 5
USERCOMMENT Test 2
4

5 回答 5

2

问题是您的顶级对象不是 NSArray,而是 NSDictionary。如果你发回一个数组,那将正常工作。另一种方法是获取顶级字典的键并在迭代之前对其进行排序。

于 2012-07-07T18:00:04.253 回答
0

字典的条目是无序的。当您遍历字典时,您可以按任何顺序获取键。

于 2012-07-07T17:58:43.863 回答
0

你不能这样做,除非你编写自己的 JSON 解析器。任何自尊的 JSON 库都不能保证你的顺序,如果它想符合 JSON 规范。

从 JSON 对象的定义来看:

键值对的无序集合。

于 2012-07-07T18:00:38.487 回答
0

对于那些仍然对解决方案感兴趣的人:

NSDictionary *userData = [update JSONValue];
NSArray *keys = [[userData allKeys] sortedArrayUsingSelector:@selector(compare:)];
NSMutableArray *array = [NSMutableArray arrayWithCapacity: [keys count]];

int i = 0;
for (NSString *key in keys) {
    [array addObject: [userData objectForKey: key]];
    i++;
}

for (NSDictionary *myDict in array) {
    NSString *comment = [myDict objectForKey:@"comment"];
    NSLog(@"USERCOMMENT %@", comment);
}

按顺序返回 JSON:

USERCOMMENT Test 6
USERCOMMENT Test 5
USERCOMMENT Test 4
USERCOMMENT Test 3
USERCOMMENT Test 2
USERCOMMENT Test 1
于 2012-07-07T21:26:19.750 回答
0

这可能与您无关,但我总是在服务器上进行排序并发回有序的 JSON 字符串。

于 2012-07-07T18:42:45.447 回答