When I read the JSON string to be a dictionary, the dictionary order is different from the JSON string original order. Is there anyone knows how to solve it? Maybe someone will tell me the dictionary is disorderly, however, our project needs sort the dictionary by JSON string original order.
-
3If a certain order is mandatory a dictionary is the wrong collection type.vadian– vadian2017-07-26 07:03:38 +00:00Commented Jul 26, 2017 at 7:03
-
If you need ordered data, using Dictionary doesn't make sense. But if you still want to do it, you have to create a custom dictionary. Though not ideally advisable, Check this link - cocoawithlove.com/2008/12/… Otherwise you can save the order of keys in an array and then get the data from dictionary on the order of array if absolutely necessary.Kapil G– Kapil G2017-07-26 07:06:02 +00:00Commented Jul 26, 2017 at 7:06
-
You should store each json Dict to array to get it orderedPrashant Tukadiya– Prashant Tukadiya2017-07-26 07:25:30 +00:00Commented Jul 26, 2017 at 7:25
1 Answer
A JSON object is define in the JSON spec as an unordered collection.
An object is an unordered set of name/value pairs. (http://json.org/)
Here are some possible solutions:
- Change the JSON object to an array of objects. If you control the server this is by far the best option. If order is important the an array is the right choice.
- Send the order along with the JSON. You can have an array of the keys also included in the JSON. Again, you would need to have control of the server to do this.
- Sort the keys after you get them. This can only work if the order that you want can be derived from the keys. For example if the keys are alphabetical or are numbers. If you control the keys (even if you don't control the entire server response) you can hack this by change the keys to be sortable in a way that works for you (for example change the keys from ["stores","locations"] to ["0_stores","1_locations"]. This can also work if you know all the possible keys and their order.
Order the keys by the location in the JSON dictionary. If the keys in the JSON are guaranteed to not show up any where else in the JSON (i.e. there is no arbitrary text field in the JSON) then you can get all the dictionary keys sorted by looking where they appear in the JSON string:
NSArray* sortedKeys = [[dictionary allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString* key1, NSString* key2) { NSInteger location1 = [jsonString rangeOfString:key1].location; NSInteger location2 = [jsonString rangeOfString:key2].location; return [@(location1) compare:@(location2)]; }];If none of these options work for you then you would have find or create your own JSON parser that respects order. I think it will be hard to find such a library, since it would be explicitly against the JSON spec. I do not recommend this option.