g r
g r

Reputation: 65

xcode sorting json in alphabetical when should not be sorting at all

I have a script that seems to be sorting a resulting JSon into some other order.

The outputted json from a php script is like so

{result:
    {pizza:
        {more nodes etc.....
         }
    },
    {pasta:
        {more nodes etc.....
         }
    },
    {sides:
        {more nodes etc.....
         }
    },
    {salads:
        {more nodes etc.....
         }
    },  
    {desserts:
         {more nodes etc.....
         }
    }
}

I then use this code in Xcode for JSon serialisation:

 NSMutableDictionary *res = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableLeaves error:&myError];

if i display results in the console the json lists in alphabetical order (which is not the original output) like so

{result:
    {desserts:
         {more nodes etc.....
         }
    },
    {pasta:
        {more nodes etc.....
         }
    },
    {pizza:
        {more nodes etc.....
         }
    },
    {salads:
        {more nodes etc.....
         }
    },  
    {sides:
        {more nodes etc.....
         }
    }


}

I do not have any sorting options listed in my code anywhere at this point and as you can see it has sorted the json result

then if i run this piece of code displaying the keys only:

NSLog(@"data %@",[[res objectForKey:@"results"]allKeys]);

i get this result:

data (
    pasta,
    pizza,
    sides,
    salad,
    desserts
)

Alphabetically the first element has been put to the bottom

I don't want any sorting at all as the sorting has been handled by the php script

any ideas?

Upvotes: 1

Views: 206

Answers (1)

zaph
zaph

Reputation: 112857

This is not JSON, it is an NSMutableDictionary. Dictionaries have no order, the display code is doing the sorting you see.

If you want an order that order must be explicitly supplied in the JSON, the order of dictioary items is not sufficient for specifying the order.

Alternatively you can parse the JSON yourself to determine the order but that order will have to be maintained other than in the dictionary. Perhaps in an associated array of dictionary key names.

Upvotes: 1

Related Questions