首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在C#中将字典转换为JSON字符串?

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

Stack Overflow用户
提问于 2011-04-08 23:31:19
回答 11查看 348.2K关注 0票数 157

我想把我的Dictionary<int,List<int>>转换成JSON字符串。有人知道如何在C#中实现这一点吗?

EN

回答 11

Stack Overflow用户

发布于 2014-09-12 06:24:31

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

return JsonConvert.SerializeObject( myDictionary );

与JavaScriptSerializer相反,myDictionary不必是<string, string>类型的字典,JsonConvert就可以工作。

票数 146
EN

Stack Overflow用户

发布于 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]}]
票数 22
EN

Stack Overflow用户

发布于 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);
票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5597349

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档