1

When I have dictionary (IDictionary) items (in C#) with random string keys, I get the JSON object as:

{
"Y21qf39sXRU=":"A",
"/N+BQBzpdkA=":"A+",
"HQ5dFtxIsGo=":"B",
"2i4tdo427Sw=":"ACCOUNTANT",
"W6EuZP1+iKY=":"Accountant",
"eaSybclf0ww=":"Client", .... //and so on

But when I change keys to numeric keys, items in the dictionary gets sorted by keys as :

{
"1":"Closed Accounts",
"260":"A",
"283":"Client",
"334":"Accountant",
"437":"new CATEGORY",
"757":"Prospect",
"973":"A+",
"1099":"B", ....

Why is Newtonsoft.JSON serializer doing this and how to avoid sorting on numeric keys?

I want results as ordered in first JSON (as coming sorted from database). I know I can again do sorting of results, but for now I want to avoid doing that.

Guanxi
  • 3,103
  • 21
  • 38
  • 4
    A dictionary inherently has no sort order. From the perspective of the dictionary's public contract, either "sort order" (since something has to come first while serialized) is just as good as the other. If you care about the order of keys, a dictionary is not the best structure. – Eric J. May 01 '15 at 16:30
  • Why do you care how your json keys are ordered? Consumers should never care about the order of json keys. (http://stackoverflow.com/questions/4515676/keep-the-order-of-the-json-keys-during-json-conversion-to-csv) – Kirk Woll May 01 '15 at 16:37
  • The issue here isn't Json.NET, the issue here is that, for the, c# generic dictionary. [The order in which the items are returned is undefined.](https://msdn.microsoft.com/en-us/library/xfhwa508%28v=vs.110%29.aspx) I.e. the items are returned in internal hash order, and the order may change if the table is rehashed. AFAIK there's no builtin c# collection with both hashed key access and index access, but since your keys & values are strings you could wrap [`NameValueCollection`](https://msdn.microsoft.com/en-us/library/system.collections.specialized.namevaluecollection%28v=vs.110%29.aspx) – dbc May 01 '15 at 17:11

1 Answers1

4

By definition, a dictionary is unordered. How it ends up being ordered is often the result of some hash function. Indeed, it's not even certain to produce the same order twice in a row with the same data set. Some implementations will maintain order as a courtesy, or if you force it with some flag, but these are hacks. If you need something to be ordered, you need to use a different data structure. Unfortunately for you, JSON's only other structure is the array, so use an array. If you have to have pairs, use an array of dictionaries where each dictionary has only a single key-value pair.

i_am_jorf
  • 53,608
  • 15
  • 131
  • 222
  • Only a note, "by definition, a `Dictionary<,>`", because `SortedDictionary<,>` is an `IDictionary<,>`, names itself a "dictionary", but is sorted. – xanatos May 01 '15 at 17:10
  • 1
    My bad really ... I should have known this. This is what happens when you miss basics. Thanks guys. – Guanxi May 01 '15 at 17:26