You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何以最简方式将JSON文件转换为C#的Dictionary<string, string>?

将JSON数组转换为C# Dictionary<string, string>的最简方法

你的JSON是包含多个键值对对象的数组,这里分两种常见需求给出最简实现:

1. 将整个JSON数组转为List<Dictionary<string, string>>

每个JSON对象对应一个Dictionary<string, string>,适合保留所有键值对的场景。

使用.NET自带的System.Text.Json(无需额外安装包)

using System.Text.Json;
using System.IO;

// 读取JSON文件内容
string jsonText = File.ReadAllText("你的JSON文件路径.json");

// 反序列化得到字典列表
List<Dictionary<string, string>> dictList = JsonSerializer.Deserialize<List<Dictionary<string, string>>>(jsonText);

使用Newtonsoft.Json(需先安装NuGet包Newtonsoft.Json)

using Newtonsoft.Json;
using System.IO;

string jsonText = File.ReadAllText("你的JSON文件路径.json");
List<Dictionary<string, string>> dictList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(jsonText);

2. 将id作为Key、data作为Value生成单个Dictionary<string, string>

如果目标是建立id到data的映射,可按以下方式处理:

使用System.Text.Json

using System.Text.Json;
using System.IO;
using System.Linq;

string jsonText = File.ReadAllText("你的JSON文件路径.json");

// 先反序列化为对象列表再转换为字典
var items = JsonSerializer.Deserialize<List<{ string data; string id; }>>(jsonText);
Dictionary<string, string> resultDict = items.ToDictionary(item => item.id, item => item.data);

使用Newtonsoft.Json

using Newtonsoft.Json;
using System.IO;
using System.Linq;

string jsonText = File.ReadAllText("你的JSON文件路径.json");
var items = JsonConvert.DeserializeObject<List<dynamic>>(jsonText);
Dictionary<string, string> resultDict = items.ToDictionary(item => item.id.ToString(), item => item.data.ToString());

内容的提问来源于stack exchange,提问作者Shax

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 23:27:20