如何在 C# 中将字典转换为 JSON 字符串?
问题描述:
我想将我的 Dictionary
转换为 JSON 字符串.有谁知道如何在 C# 中实现这一点?
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.
对于您指定的 Dictionary
,您可以使用 Linq:
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) + "}";
}
但是,如果您要序列化多个不同的类或更复杂的数据结构,或者特别是如果您的数据包含字符串值,则最好使用信誉良好的已经知道如何处理转义字符和换行符等问题的 JSON 库.Json.NET 是一种流行的选择.