Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Serialize Dictionary<ulong,ulong> to JSON

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?

like image 365
Mark Richman Avatar asked Sep 10 '10 15:09

Mark Richman


3 Answers

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.

like image 150
Mark Richman Avatar answered Oct 14 '22 14:10

Mark Richman


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

Ex:

JsonConvert.SerializeObject(mydict);
like image 28
Binod Mahto Avatar answered Oct 14 '22 14:10

Binod Mahto


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)

like image 21
Michael Freidgeim Avatar answered Oct 14 '22 13:10

Michael Freidgeim