我想把我的Dictionary<int,List<int>>
转换成JSON字符串。有人知道如何在C#中实现这一点吗?
发布于 2014-09-12 06:24:31
This answer提到了Json.NET,但没有告诉您如何使用Json.NET序列化字典:
return JsonConvert.SerializeObject( myDictionary );
与JavaScriptSerializer相反,myDictionary
不必是<string, string>
类型的字典,JsonConvert就可以工作。
发布于 2011-04-08 23:45:35
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]}]
发布于 2011-04-08 23:46:33
如果语法有点小,我很抱歉,但我从中获得的代码最初是在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);
https://stackoverflow.com/questions/5597349
复制相似问题