JSONKit: how to keep order of JSON dictionary keys

杀马特。学长 韩版系。学妹 提交于 2019-12-12 04:35:49

问题


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?


回答1:


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



回答2:


Dictionaries are not ordered, but arrays are, so if you can change your JSON data structure to an array, you should get an ordered result.

[{'key1':'value1'},{'key2':'value2'},{'key3':'value3'}]

What does your data look like?



来源:https://stackoverflow.com/questions/13551224/jsonkit-how-to-keep-order-of-json-dictionary-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!