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

dae*_*aai 122 c# json dictionary

我想将我转换Dictionary<int,List<int>>为JSON字符串.有谁知道如何在C#中实现这一目标?

gil*_*ly3 112

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

对于Dictionary<int, List<int>>您指定的,您可以使用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) + "}";
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您要序列化几个不同的类或更复杂的数据结构,或者特别是如果您的数据包含字符串值,那么最好使用已知道如何处理转义字符和换行符之类的信誉良好的JSON库. Json.NET是一个受欢迎的选择.

  • @Jacob - 天真?哎哟.就个人而言,我无法证明包含*另一个*程序集的理由,当我需要做的只需一个简短的方法即可完成. (122认同)
  • 这个解决方案充其量是天真的.使用真正的json序列化库. (60认同)
  • dict.add("RandomKey \"","RandomValue \""); BOOOOOOOOOOOOOOOOM.天真无邪.使用真正的json序列化库. (31认同)
  • 还有一个关于gilly3评论的评论.有时你在Windows Phone上编码.你正在添加zlip,twitter,谷歌,音频处理的东西,图像处理的东西.如果你的用法很简单,你最好实现像它这样的简单方法,以及一些用于社交媒体交互的基本HttpRequests.添加程序集时,您始终必须处理错误,并且无法获得精简版本.顺便说一句,在json libs中,有这样的天真方法,没有魔法. (15认同)
  • 每个打开的项目都应该有一个页面告诉你:"嘿,大多数时候,你只需要执行这10行算法.这是代码." (13认同)
  • @JamesNewton-King - 完成.有趣的是,雅各布的评论以及随之而来的赞成使我感到困惑.Sleeper的评论让我感到困惑,但它至少让我思考.我从来没有想到读者正在考虑我的序列化字符串的方法."当然这对字符串来说是一种糟糕的方法",我想,"这显然是*." 我现在明白了仇敌.这个问题可能在序列化字典的搜索结果中排名很高,但我的答案并不是一个很好的通用答案,用于序列化任何`IDictionary <TKey,TValue>`.对不起这么盲目! (12认同)
  • 对于使用字符串键或值的字典,这不是一个好的答案.双引号,斜杠和换行符都会导致JSON损坏.应该更新它以包含警告. (4认同)
  • @jonny - [LINQ](http://msdn.microsoft.com/en-us/library/bb397926.aspx)内置于.Net.它不是外国图书馆. (2认同)

Dav*_*edy 100

这个答案提到了Json.NET,但没有告诉你如何使用Json.NET来序列化字典:

return JsonConvert.SerializeObject( myDictionary );
Run Code Online (Sandbox Code Playgroud)

与JavaScriptSerializer相反,myDictionary不必是<string, string>JsonConvert 的类型字典.


Jim*_* G. 71

Json.NET现在可以充分地序列化C#词典,但是当OP最初发布这个问题时,许多MVC开发人员可能已经使用了JavaScriptSerializer类,因为这是开箱即用的默认选项.

如果您正在处理遗留项目(MVC 1或MVC 2),并且您无法使用Json.NET,我建议您使用List<KeyValuePair<K,V>>而不是使用Dictionary<K,V>>.遗留的JavaScriptSerializer类会很好地序列化这种类型,但它会出现字典问题.

文档:使用Json.NET序列化集合

  • asp.net mvc3和mvc4用户的完美答案 (3认同)

Mer*_*itt 19

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, List<int>> foo = new Dictionary<int, List<int>>();

            foo.Add(1, new List<int>( new int[] { 1, 2, 3, 4 }));
            foo.Add(2, new List<int>(new int[] { 2, 3, 4, 1 }));
            foo.Add(3, new List<int>(new int[] { 3, 4, 1, 2 }));
            foo.Add(4, new List<int>(new int[] { 4, 1, 2, 3 }));

            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Dictionary<int, List<int>>));

            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, foo);
                Console.WriteLine(Encoding.Default.GetString(ms.ToArray()));
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这将写入控制台:

[{\"Key\":1,\"Value\":[1,2,3,4]},{\"Key\":2,\"Value\":[2,3,4,1]},{\"Key\":3,\"Value\":[3,4,1,2]},{\"Key\":4,\"Value\":[4,1,2,3]}]
Run Code Online (Sandbox Code Playgroud)


Ish*_*awa 16

如果您的上下文允许(技术限制等),请使用Newtonsoft.JsonJsonConvert.SerializeObject中的方法:它会让您的生活更轻松。

Dictionary<string, string> localizedWelcomeLabels = new Dictionary<string, string>();
localizedWelcomeLabels.Add("en", "Welcome");
localizedWelcomeLabels.Add("fr", "Bienvenue");
localizedWelcomeLabels.Add("de", "Willkommen");
Console.WriteLine(JsonConvert.SerializeObject(localizedWelcomeLabels));

// Outputs : {"en":"Welcome","fr":"Bienvenue","de":"Willkommen"}
Run Code Online (Sandbox Code Playgroud)

如果您更喜欢引用Microsoft 的System.Text.JsonJsonSerializer.Serialize ,请使用以下方法:

Console.WriteLine(JsonSerializer.Serialize(localizedWelcomeLabels));
Run Code Online (Sandbox Code Playgroud)


How*_*ulf 15

简单的单行答案

(using System.Web.Script.Serialization)

此代码将转换任何Dictionary<Key,Value>Dictionary<string,string>,然后序列化的JSON字符串:

var json = new JavaScriptSerializer().Serialize(yourDictionary.ToDictionary(item => item.Key.ToString(), item => item.Value.ToString()));
Run Code Online (Sandbox Code Playgroud)

值得注意的是,类似的东西Dictionary<int, MyClass>也可以这种方式序列化,同时保留复杂的类型/对象.


说明(细目)

var yourDictionary = new Dictionary<Key,Value>(); //This is just to represent your current Dictionary.
Run Code Online (Sandbox Code Playgroud)

您可以yourDictionary使用实际变量替换变量.

var convertedDictionary = yourDictionary.ToDictionary(item => item.Key.ToString(), item => item.Value.ToString()); //This converts your dictionary to have the Key and Value of type string.
Run Code Online (Sandbox Code Playgroud)

我们这样做,因为Key和Value必须是string类型,作为a的序列化的要求Dictionary.

var json = new JavaScriptSerializer().Serialize(convertedDictionary); //You can then serialize the Dictionary, as both the Key and Value is of type string, which is required for serialization.
Run Code Online (Sandbox Code Playgroud)

  • @Jonny您缺少参考程序集System.Web.Extensions https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx (2认同)

riw*_*alk 12

对不起,如果语法是最小的一点,但我得到的代码最初是在VB :)

using System.Web.Script.Serialization;

...

Dictionary<int,List<int>> MyObj = new Dictionary<int,List<int>>();

//Populate it here...

string myJsonString = (new JavaScriptSerializer()).Serialize(MyObj);
Run Code Online (Sandbox Code Playgroud)

  • 抛出ArgumentException:类型'System.Collections.Generic.Dictionary`2不支持字典的序列化/反序列化,键必须是字符串或对象. (2认同)

小智 11

网络核心:System.Text.Json.JsonSerializer.Serialize(dict)


Sal*_*lim 7

你可以使用System.Web.Script.Serialization.JavaScriptSerializer:

Dictionary<string, object> dictss = new Dictionary<string, object>(){
   {"User", "Mr.Joshua"},
   {"Pass", "4324"},
};

string jsonString = (new JavaScriptSerializer()).Serialize((object)dictss);
Run Code Online (Sandbox Code Playgroud)


Sko*_*šek 6

在Asp.net核心使用:

using Newtonsoft.Json

var obj = new { MyValue = 1 };
var json = JsonConvert.SerializeObject(obj);
var obj2 = JsonConvert.DeserializeObject(json);
Run Code Online (Sandbox Code Playgroud)

  • @vapcguy是的,Newtonsoft是第三方,但在他们的产品中也被MS广泛使用和采用.https://www.nuget.org/packages/Newtonsoft.Json/ (2认同)