如何在C#中将字典转换为JSON字符串?

时间:2011-04-08 15:31:19

标签: c# json dictionary

我想将Dictionary<int,List<int>>转换为JSON字符串。有谁知道如何在C#中实现这个目标?

13 个答案:

答案 0 :(得分:107)

序列化数据结构仅包含数值或布尔值非常简单。如果您没有太多序列化,可以为您的特定类型编写一个方法。

对于您指定的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是一种受欢迎的选择。

答案 1 :(得分:70)

Json.NET现在可能充分地序列化C#词典,但是当OP最初发布这个问题时,许多MVC开发人员可能一直在使用JavaScriptSerializer类,因为这是开箱即用的默认选项。 / p>

如果您正在处理遗留项目(MVC 1或MVC 2),并且无法使用Json.NET,我建议您使用List<KeyValuePair<K,V>>而不是Dictionary<K,V>>。遗留的JavaScriptSerializer类会很好地序列化这种类型,但它会出现字典问题。

文档: Serializing Collections with Json.NET

答案 2 :(得分:69)

This answer提到了Json.NET,但没有告诉你如何使用Json.NET来序列化字典:

return JsonConvert.SerializeObject( myDictionary );

与JavaScriptSerializer相反,myDictionary不一定是JsonConvert类型<string, string>的字典。

答案 3 :(得分:17)

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]}]

答案 4 :(得分: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);

答案 5 :(得分:11)

简单的单行答案

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()));

值得注意的是,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.

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

答案 6 :(得分:7)

您可以使用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);

答案 7 :(得分:5)

在Asp.net核心使用:

using Newtonsoft.Json

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

答案 8 :(得分:1)

您可以使用JavaScriptSerializer

答案 9 :(得分:1)

似乎有很多不同的图书馆和过去几年似乎没有的东西。但是截至2016年4月,这个解决方案对我来说效果很好。 字符串很容易被ints替换

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();
    }

两个导入点。首先,请务必在Visual Studio的Solution Explorer中添加System.Runtime.Serliazation作为项目的引用。其次,添加此行,

using System.Runtime.Serialization.Json;

在文件的顶部与其余的使用,因此可以找到DataContractJsonSerializer类。这个blog post提供了有关此序列化方法的更多信息。

数据格式(输入/输出)

我的数据是一个包含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"]
 }]

答案 10 :(得分:1)

如果您的上下文允许(技术限制等),请使用Piotrminkowski Blog中的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"}

答案 11 :(得分:0)

这是仅使用Microsoft的标准.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());
}

答案 12 :(得分:0)

仅供参考,在所有较旧的解决方案中:UWP 有自己的内置 JSON 库 Windows.Data.Json

JsonObject 是可以直接用于存储数据的地图:

var options = new JsonObject();
options["foo"] = JsonValue.CreateStringValue("bar");
string json = options.ToString();
相关问题