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是一个受欢迎的选择.
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类会很好地序列化这种类型,但它会出现字典问题.
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)
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)
你可以使用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)
在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)