Search code examples
iphoneobjective-ciosjsonkit

JSONKit: how to keep order of JSON dictionary keys


I've some JSON String that represents a Map (Dictionary) from the server.

I need to draw this map as it is @ my iPhone app.

I am using JSONKit and it seems that it uses Hashing function to insert keys into its internal JKDictionary....

So should I send a priority number to order the keys? Or there is some way to make JSONKit to preserve keys ordering of the server JSON data?


Solution

  • You can choose to add a order property to your dictionary. And sort your keys using that property. Then you can enumerate your dictionary using your sorted keys. enumerateKeysAndObjectsUsingBlock:

    // Here I suppose you have added another number property `order` for your dictionary's values
    NSArray *sortedKeys = [dic keysSortedByValueUsingComparator:^(id obj1, id obj2){
        return [obj1 order] < [obj2 order];
    }];
    
    // for in will give your an ordered travel for your sortedKeys
    for (id key in sortedKeys) {
        // handle your dic
        [dic objectForKey:key];
    }