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

185
我想将我的Dictionary<int,List<int>>转换为JSON字符串。有人知道如何在C#中实现吗?

5
使用Newtonsoft.Json NuGet包。JsonConvert.SerializeObject(yourObject)。 - RayLoveless
16个回答

4

以下是如何使用来自微软的标准 .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

3

似乎在过去的几年中,许多不同的库和工具都已经出现并消失了。然而,截至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"]
 }]

2

字典可序列化吗? - Numenor
我本以为这会起作用——string json = serializer.Serialize((object)dict); - Twelve47
1
@Numenor 是的,但只有当键和值都是 string 类型时才是如此。我在这里发布了一个答案,其中包括这一点,如果你想看一下。 - EternalWulf
@HowlinWulf 更确切地说,该值不一定是字符串。但对于键,它绝不能是整数。字符串最适合作为键。 - Gyum Fox
1
@Twelve47 应该包括一个示例用法,以防链接被移动。否则,这个答案有一天可能会变得无用。 - vapcguy

2

这与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;
    }

1
仅供参考,旧解决方案中:UWP有自己内置的JSON库Windows.Data.JsonJsonObject是一个可以直接用来存储数据的映射表。
var options = new JsonObject();
options["foo"] = JsonValue.CreateStringValue("bar");
string json = options.ToString();

0

改进了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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接