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?

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.

How to maintain order when converting jsonstring to NSDictionary using NSJSONSerialization
 
 
Q