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