0

In my application I need to send a JSON to the server. The order of the JSON is important. I tried to use NSMutableDictionary and then use NSJSONSerialization to convert the dictionary to JSON. But the orderer is messed up.

What other options do I have to have a key-value structure but maintain the insertion order?

Keselme
  • 3,779
  • 7
  • 36
  • 68
  • Use an array of dictionaries and add a key-value pair that is specific for your ordering logic. – koen Nov 01 '20 at 14:38
  • Here are two more ideas, both based on the fact that an array maintains its order. First you could use a dictionary just like now but add a key e.g. ```order``` that contains an array of strings with the keys in the order you want. Secondly you could use two arrays - one containing the keys and the other the objects in the order you want. – skaak Nov 01 '20 at 15:08
  • @koen PS - I am not clear on what you suggest and may be suggesting the same, but I understand you suggestion that you use an array of dictionaries in the correct order, presumably then each dictionary having just one key and one object in it? – skaak Nov 01 '20 at 15:12
  • @skaak, but how will I convert the two arrays with `NSJSONSerialization`? – Keselme Nov 01 '20 at 15:47
  • Same as you do now with the dictionary. It (NSJSON...) takes either an array or a dictionary as top level object. So for the first suggestion there is no change and for the second you can store the two arrays themselves into an array (with two objects of course) and then use that. Alternatively you could create a dictionary top level object with two keys being say ```keys``` and ```values``` and put the arrays in there. – skaak Nov 01 '20 at 15:54
  • I see you are marked as a duplicate - in the existing answers there is an explanation of ```sortedKeys``` for JSON which looks very promising. – skaak Nov 01 '20 at 15:58
  • @skaak: yes it is the same as what you proposed, add an additional key-value pair to each dictionary in the array. – koen Nov 01 '20 at 17:01

0 Answers0