我想将我的
Dictionary<int,List<int>>
转换为JSON字符串。有人知道如何在C#中实现吗?Dictionary<int,List<int>>
转换为JSON字符串。有人知道如何在C#中实现吗?以下是如何使用来自微软的标准 .Net 库完成此操作的步骤:
using System.IO;
using System.Runtime.Serialization.Json;
private static string DataToJson<T>(T data)
{
MemoryStream stream = new MemoryStream();
DataContractJsonSerializer serialiser = new DataContractJsonSerializer(
data.GetType(),
new DataContractJsonSerializerSettings()
{
UseSimpleDictionaryFormat = true
});
serialiser.WriteObject(stream, data);
return Encoding.UTF8.GetString(stream.ToArray());
}
Dictionary<string, dynamic>
结合使用,并在一个对象中拥有所有的 JSON 原始类型,如整数、浮点数、布尔值、字符串,甚至是 null。+1 - Christos Lytras似乎在过去的几年中,许多不同的库和工具都已经出现并消失了。然而,截至2016年4月,这个解决方案对我来说效果很好。使用int轻松替换字符串。
//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();
}
有两个重要的要点。首先,请确保在Visual Studio解决方案资源管理器中将System.Runtime.Serialization添加为您项目的引用。其次,请添加以下这行代码:
using System.Runtime.Serialization.Json;
在文件顶部与其他using语句一起,加入DataContractJsonSerializer
类,以便能够找到它。这篇博客文章提供了更多关于这种序列化方法的信息。
我的数据是一个字典,包含3个字符串,每个字符串都指向一个字符串列表。这些字符串列表的长度分别为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"]
}]
你可以使用JavaScriptSerializer。
string
类型时才是如此。我在这里发布了一个答案,其中包括这一点,如果你想看一下。 - EternalWulf这与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;
}
Windows.Data.Json
。JsonObject
是一个可以直接用来存储数据的映射表。var options = new JsonObject();
options["foo"] = JsonValue.CreateStringValue("bar");
string json = options.ToString();
改进了mwjohnson的版本:
string WriteDictionaryAsJson_v2(Dictionary<string, List<string>> myDict)
{
string str_json = "";
DataContractJsonSerializerSettings setting =
new DataContractJsonSerializerSettings()
{
UseSimpleDictionaryFormat = true
};
DataContractJsonSerializer js =
new DataContractJsonSerializer(typeof(Dictionary<string, List<string>>), setting);
using (MemoryStream ms = new MemoryStream())
{
// Serializer the object to the stream.
js.WriteObject(ms, myDict);
str_json = Encoding.Default.GetString(ms.ToArray());
}
return str_json;
}