1

Is there a way to set a custom order to the elements from a JSONEncoder? For example if I have an Encodable with elements id, message, and error is there a way to make sure the JSONEncoder returns those elements in that order? Currently it seems to just return data in any order it chooses.

I know there's an option for alphabetically using JSONEncoder.OutputFormatting and .sortedkeys but that's not what I'm looking for (also that seems to only work in ios 11). I'm trying to make unit tests where I compare json strings so order is essential.

Kevin Schildhorn
  • 197
  • 2
  • 16
  • Dictionaries are inherently unordered; short of sorting the keys, there isn’t anything you can do to enforce a custom ordering unless you encode your values in an array. Is there a reason you need a specific ordering? – Itai Ferber May 10 '18 at 16:37
  • The reason I'm looking for a specific ordering is because I am testing the Encoding using Unit Tests, and I'm comparing the result to a predefined json string. – Kevin Schildhorn May 10 '18 at 16:42
  • 1
    Can't you sort the keys in the predefined string alphabetically and then use the sorted keys options? – dan May 10 '18 at 16:56
  • @Kevin How about you re-read the produced output with `JSONSerialization` and compare to actual values (e.g. dictionaries and strings and arrays and numbers)? Then you're not beholden to any ordering. – Itai Ferber May 10 '18 at 16:58
  • @dan My current device is running 10.3.2 and the sorted keys option only works on ios 11 and above. I suppose I could try to find another device running 11 and do the testing with that. – Kevin Schildhorn May 10 '18 at 17:22
  • @ItaiFerber I could potentially do it that way, although the strings are meant to be sent from a server so I'd prefer a string. – Kevin Schildhorn May 10 '18 at 17:22
  • Do not allow your tests to force order on a dictionary output. Dictionaries do not guarantee their order for a reason (as usual: efficiency). There is the usual way around this (add another level of indirection) which some languages (e.g. ruby) have been taking, but Swift has not gone that route which is a _good thing (TM)_. Please bear the consequences and either search for string presence (not position) or use another way to define your test result. Do not try to force this on `JSONEncoder`, it is not its duty! – Patru May 10 '18 at 18:52
  • Then what is the point of JSONEncoder.OutputFormatting? – Kevin Schildhorn May 10 '18 at 18:57
  • @Kevin Is the server guaranteeing that it will send you the output string in the same order every time? If you send data back to the server, does it require that same ordering too? At runtime, the ordering is meaningless; all you really care about is that the payloads are equal. This isn't necessarily a good reason to overcomplicate the test (but of course, that's up to your judgement). – Itai Ferber May 10 '18 at 19:55

0 Answers0