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

查看:196
本文介绍了如何在 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 是一种流行的选择.

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

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