如何将字典转换为C#中的JSONstring?

我想将我的Dictionary<int,List<int>>为JSONstring。 有谁知道如何在C#中实现这一点?

序列化仅包含数值或布尔值的数据结构相当简单。 如果你没有太多的序列化,你可以为你的特定types写一个方法。

对于一个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) + "}"; } 

但是,如果要序列化几个不同的类或更复杂的数据结构, 或者尤其是在数据包含string值的情况下 ,最好使用已知道如何处理转义字符和换行符等信誉良好的JSON库。 Json.NET是一个受欢迎的选项。

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

如果您正在使用传统项目(MVC 1或MVC 2),并且无法使用Json.NET,则build议您使用List<KeyValuePair<K,V>>而不是Dictionary<K,V>> 。 传统的JavaScriptSerializer类将序列化这种types,但它会有字典的问题。

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

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

 return JsonConvert.SerializeObject( myDictionary ); 

与JavaScriptSerializer相反, myDictionary不一定是JsonConvert工作的<string, string>types的字典。

对不起,如果语法是最微小的一点,但我得到这个从最初是在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); 
 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())); } } } } 

这将写入控制台:

 [{\"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]}] 

您可以使用JavaScriptSerializer将字典转换为JSONstring

需要使用扩展using System.Web.Script.Serialization;

 Dictionary<string, object> dictss = new Dictionary<string, object>(); dictss.Add("Method", "LOGIN"); dictss.Add("User", "User_Name"); dictss.Add("Pass", "Password"); dictss.Add("Type", "User_Type"); Dictionary<string, object> skills = new Dictionary<string, object>(); skills.Add("1", "SKILL-1"); skills.Add("2", "SKILL-2"); skills.Add("3", "SKILL-3"); dictss.Add("Skill", skills); JavaScriptSerializer serializer = new JavaScriptSerializer(); string jsonString = serializer.Serialize((object)dictss); 

简单的单线答案

此代码将任何Dictionary<Key,Value>转换为Dictionary<string,string> ,然后将其序列化为JSONstring:

 var json = new JavaScriptSerializer().Serialize(yourDictionary.ToDictionary(item => item.Key.ToString(), item => item.Value.ToString())); 

值得注意的是像Dictionary<int, MyClass>这样的东西也可以用这种方式序列化,同时保留复杂的types/对象。


说明(细目)

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

你可以用你的实际variablesreplacevariablesyourDictionary

 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. 

我们这样做是因为Key和Value都必须是stringtypes,这是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. 

在Asp.net核心使用:

 using Newtonsoft.Json var obj = new { MyValue = 1 }; var json = JsonConvert.SerializeObject(obj); var obj2 = JsonConvert.DeserializeObject(json); 

你可以使用JavaScriptSerializer 。

似乎有很多不同的图书馆,而且前些年似乎没有什么变化。 不过截至2016年4月,这个解决scheme对我来说效果不错。 string很容易被int取代

TL / DR; 复制这个,如果这是你来这里的:

  //outputfilename will be something like: "C:/MyFolder/MyFile.txt" void WriteDictionaryAsJson(Dictionary<string, List<string>> myDict, string outputfilename) { DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Dictionary<string, List<string>>)); MemoryStream ms = new MemoryStream(); js.WriteObject(ms, myDict); //Does the serialization. StreamWriter streamwriter = new StreamWriter(outputfilename); streamwriter.AutoFlush = true; // Without this, I've run into issues with the stream being "full"...this solves that problem. ms.Position = 0; //ms contains our data in json format, so let's start from the beginning StreamReader sr = new StreamReader(ms); //Read all of our memory streamwriter.WriteLine(sr.ReadToEnd()); // and write it out. ms.Close(); //Shutdown everything since we're done. streamwriter.Close(); sr.Close(); } 

两个import点。 首先,确保在Visual Studio的解决scheme资源pipe理器中的项目中添加System.Runtime.Serliazation作为参考。 其次,加上这一行,

 using System.Runtime.Serialization.Json; 

在文件的顶部与其余的使用,所以DataContractJsonSerializer类可以find。 这篇博文有更多关于这种序列化方法的信息。

数据格式(input/输出)

我的数据是一个包含3个string的字典,每个string都指向一个string列表。 string列表的长度为3,4和1.数据如下所示:

 StringKeyofDictionary1 => ["abc","def","ghi"] StringKeyofDictionary2 => ["String01","String02","String03","String04"] Stringkey3 => ["someString"] 

写入文件的输出将在一行上,这里是格式化的输出:

  [{ "Key": "StringKeyofDictionary1", "Value": ["abc", "def", "ghi"] }, { "Key": "StringKeyofDictionary2", "Value": ["String01", "String02", "String03", "String04", ] }, { "Key": "Stringkey3", "Value": ["SomeString"] }] 

这与Meritt之前发布的类似。 只是发布完整的代码

  string sJSON; Dictionary<string, string> aa1 = new Dictionary<string, string>(); aa1.Add("one", "1"); aa1.Add("two", "2"); aa1.Add("three", "3"); Console.Write("JSON form of Person object: "); sJSON = WriteFromObject(aa1); Console.WriteLine(sJSON); Dictionary<string, string> aaret = new Dictionary<string, string>(); aaret = ReadToObject<Dictionary<string, string>>(sJSON); public static string WriteFromObject(object obj) { byte[] json; //Create a stream to serialize the object to. using (MemoryStream ms = new MemoryStream()) { // Serializer the object to the stream. DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType()); ser.WriteObject(ms, obj); json = ms.ToArray(); ms.Close(); } return Encoding.UTF8.GetString(json, 0, json.Length); } // Deserialize a JSON stream to object. public static T ReadToObject<T>(string json) where T : class, new() { T deserializedObject = new T(); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) { DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedObject.GetType()); deserializedObject = ser.ReadObject(ms) as T; ms.Close(); } return deserializedObject; }