如何转换字典来一个JSON字符串在C#中? [英] How do I convert a dictionary to a JSON String in C#?

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

问题描述

我想我的词典&LT转换,INT,列表与LT; 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.

对于词典&LT; INT,列表与LT; INT&GT;&GT; 为您指定,您可以使用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 是一个受欢迎的选择。

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

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