C# Serialize Dictionary to JSON

后端 未结 3 1834
没有蜡笔的小新
没有蜡笔的小新 2021-02-14 08:54

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

new JavaScriptSerializer().Serialize(mydict)`

Ty

相关标签:
3条回答
  • 2021-02-14 09:34

    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)

    0 讨论(0)
  • 2021-02-14 09:36

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

    Ex:

    JsonConvert.SerializeObject(mydict);
    
    0 讨论(0)
  • 2021-02-14 09:37
    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.

    0 讨论(0)
提交回复
热议问题