How do I convert a dictionary to a JSON String in C#?

daehaai picture daehaai · Apr 8, 2011 · Viewed 296.8k times · Source

I want to convert my Dictionary<int,List<int>> to JSON string. Does anyone know how to achieve this in C#?

Answer

gilly3 picture gilly3 · Apr 8, 2011

Serializing data structures containing only numeric or boolean values is fairly straightforward. If you don't have much to serialize, you can write a method for your specific type.

For a Dictionary<int, List<int>> as you have specified, you can use Linq:

string MyDictionaryToJson(Dictionary<int, List<int>> dict)
{
    var entries = dict.Select(d =>
        string.Format("\"{0}\": [{1}]", d.Key, string.Join(",", d.Value)));
    return "{" + string.Join(",", entries) + "}";
}

But, if you are serializing several different classes, or more complex data structures, or especially if your data contains string values