Dictionary<int,List<int>>
转换为JSON字符串。有人知道如何在C#中实现吗?Dictionary<int,List<int>>
转换为JSON字符串。有人知道如何在C#中实现吗?这个答案提到了Json.NET,但没有告诉你如何使用Json.NET来序列化一个字典:
return JsonConvert.SerializeObject( myDictionary );
与JavaScriptSerializer不同的是,myDictionary
不必是类型为 <string, string>
的字典才能使 JsonConvert 正常工作。仅包含数字或布尔值的数据结构序列化相对简单。如果您需要序列化的内容不多,可以为您特定的类型编写一个方法。
对于您指定的 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) + "}";
}
但是,如果你要序列化几个不同的类或更复杂的数据结构,特别是当你的数据包含字符串值时,最好使用一个可靠的JSON库,它已经知道如何处理转义字符和换行符。 Json.NET 是一个受欢迎的选择。
Json.NET 可能已经能够充分地序列化 C# 字典,但在 OP 最初发布这个问题时,许多 MVC 开发人员可能使用 JavaScriptSerializer 类,因为它是开箱即用的默认选项。
如果你正在处理旧项目(MVC 1 或 MVC 2),且不能使用 Json.NET,我建议你使用 List<KeyValuePair<K,V>>
而不是 Dictionary<K,V>>
。旧版 JavaScriptSerializer 类会很好地序列化该类型,但对字典则存在问题。
(使用 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()));
值得注意的是,像Dictionary<int,MyClass>
这样的东西也可以以这种方式进行序列化,同时保留复杂类型/对象。
var yourDictionary = new Dictionary<Key,Value>(); //This is just to represent your current Dictionary.
您可以将变量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.
我们这样做的原因是,因为键和值都必须是字符串类型,这是序列化 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.
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]}]
如果语法有一点点错误,请见谅,因为我从最初的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);
JsonConvert.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"}
在 Asp.net Core 中使用:
using Newtonsoft.Json
var obj = new { MyValue = 1 };
var json = JsonConvert.SerializeObject(obj);
var obj2 = JsonConvert.DeserializeObject(json);
System.Core
,然后尝试引用 using Newtonsoft.Json
,但是没有成功。我认为 Newtonsoft
是一个第三方库。 - vapcguyNet Core: 使用System.Text.Json.JsonSerializer.Serialize方法对字典进行序列化。
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);