How to maintain order when converting jsonstring to NSDictionary using NSJSONSerialization

    NSString *jsonString = @"{\"key1\":\"value1\",\"key2\":\"value2\",\"key3\":\"value3\",\"key4\":\"value4\"}";
    NSString *jsonString2 = @"{\"key2\":\"value2\",\"key1\":\"value1\",\"key4\":\"value4\",\"key3\":\"value3\"}";
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSData *jsonData2 = [jsonString2 dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dict1 = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    NSDictionary *dict2 = [NSJSONSerialization JSONObjectWithData:jsonData2 options:NSJSONReadingMutableContainers error:nil];

The expected results are:

  • dict1:key1,key2,key3,key4

  • dict2:key2,key1,key4,key3

Is there any way to make that happen?

Replies

NSDictionary doesn't make any guarantee about order, it's a data structure that is not meant to be ordered, so it's not a surprise the result looks like that. There is a NSJSONWritingSortedKeys option if you want things in lexicographic order when converting from NSObjects to json. If not you will have to use an NSArray.

  • thanks NSJSONWritingSortedKeys option is passed in during serialization, but my issue occurs during deserialization, so it is not applicable.

  • Neither does JSON has any concept of ordering for JSON objects. Array elements may keep the insertion order, when deserialised, but not after they are put into an unordered dictionary. Why do you want the order in the first place? If you do, move the elements to some ordered data structure or sort them after deserialisation.

Add a Comment