10

I am trying to serialize a Dictionary to JSON, and get the following exception:

new JavaScriptSerializer().Serialize(mydict)`

Type 'System.Collections.Generic.Dictionary`2[[System.UInt64, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Nullable`1[[System.UInt64, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' is not supported for serialization/deserialization of a dictionary, keys must be strings or objects.

Is there an easy way to do this? Maybe converting the ulongs to strings via LINQ or something relatively terse?

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
Mark Richman
  • 28,948
  • 25
  • 99
  • 159
  • 1
    This is such an awful error message, isn't a value object still an object? – JoshBerke May 13 '11 at 14:32
  • possible duplicate of [How do I convert a dictionary to a JSON String in C#?](http://stackoverflow.com/questions/5597349/how-do-i-convert-a-dictionary-to-a-json-string-in-c) – Jim G. Mar 07 '14 at 16:39
  • 1
    I clearly posted the question first. Why isn't the other one marked as a duplicate? – Mark Richman Mar 07 '14 at 20:18

3 Answers3

18
var dict = mapping.ToDictionary(item => item.Key.ToString(), item => item.Value.ToString());`

that will convert any Dictionary<K,V> to Dictionary<string,string> and serialization then works.

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
Mark Richman
  • 28,948
  • 25
  • 99
  • 159
  • 1
    This works perfectly. Worthwhile to note that something like a Dictionary can also be serialized in this way while preserving the complex type: mapping.ToDictionary(item => item.Key.ToString(), item => item.Value); – John Nelson Apr 05 '11 at 15:10
3

use NewtonSoft.Json instead of JavaScriptSerializer to overcome this problem:

Ex:

JsonConvert.SerializeObject(mydict);
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
Binod Mahto
  • 340
  • 2
  • 13
1

The blog http://dukelupus.wordpress.com/2011/05/04/asp-net-mvc-json-and-a-generic-dictionary/ describes an extension method Dictionary ToJsonDictionary(this Dictionary input)

Michael Freidgeim
  • 26,542
  • 16
  • 152
  • 170
  • While this answer is several years old [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – Taryn Mar 09 '14 at 13:57