如何将Dictionary序列化为JSON对象数组?
将C# Dictionary转换为指定格式的JSON
要把你的Dictionary<string, string>转换成目标JSON数组,核心是先把字典的键值对映射为包含key和val属性的对象列表,再序列化这个列表即可。以下是两种常用的实现方式:
使用Newtonsoft.Json(Json.NET)
这是.NET生态中广泛使用的JSON处理库,需先通过NuGet安装Newtonsoft.Json包:
using Newtonsoft.Json; using System.Collections.Generic; using System.Linq; var tableData = new Dictionary<string, string>(); tableData["name"] = "Sam"; tableData["city"] = "Wellington"; tableData["country"] = "New Zealand"; // 将字典键值对转换为目标结构的对象列表 var targetList = tableData.Select(kv => new { key = kv.Key, val = kv.Value }).ToList(); // 序列化为带缩进的JSON字符串 string jsonOutput = JsonConvert.SerializeObject(targetList, Formatting.Indented); // 输出结果 Console.WriteLine(jsonOutput);
使用System.Text.Json(.NET Core 3.0+ / .NET 5+ 内置)
如果使用较新的.NET版本,可直接用内置的System.Text.Json库,无需额外安装:
using System.Text.Json; using System.Collections.Generic; using System.Linq; var tableData = new Dictionary<string, string>(); tableData["name"] = "Sam"; tableData["city"] = "Wellington"; tableData["country"] = "New Zealand"; var targetList = tableData.Select(kv => new { key = kv.Key, val = kv.Value }).ToList(); // 配置序列化选项,生成带缩进的格式 var serializeOptions = new JsonSerializerOptions { WriteIndented = true }; string jsonOutput = JsonSerializer.Serialize(targetList, serializeOptions); Console.WriteLine(jsonOutput);
两种方式最终都会输出你需要的JSON格式:
[ { "key": "name", "val": "Sam" }, { "key": "city", "val": "Wellington" }, { "key": "country", "val": "New Zealand" } ]
内容的提问来源于stack exchange,提问作者Hooman Bahreini
相关产品推荐
相关产品推荐

