且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 C# 中将字典转换为 JSON 字符串?

更新时间:2023-01-16 10:58:54

序列化数据结构仅包含数字或布尔值是相当简单的.如果您没有太多要序列化的内容,您可以为您的特定类型编写一个方法.

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 是一种流行的选择.