如何将字典转换为C#中的JSON字符串? [英] How do I convert a dictionary to a JSON String in C#?

查看:907
本文介绍了如何将字典转换为C#中的JSON字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的 Dictionary< int,List< int>> 转换为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< int,List< int> ;< / code>如您所指定的那样,您可以使用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 是一个受欢迎的选项。

But, if you are serializing several different classes, or more complex data structures, or especially if your data contains string values, you would be better off using a reputable JSON library that already knows how to handle things like escape characters and line breaks. Json.NET is a popular option.

这篇关于如何将字典转换为C#中的JSON字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆