如何用NewtonSoft在C#中获取JSON动态键的Profile名称?
动态获取JSON中随机键对应的Profile名称(C# + Json.NET)
需求:使用NewtonSoft.Json(Json.NET)读取JSON文件,获取profiles节点下所有随机生成的键对应的name属性值,无需创建固定实体类,适配JSON的动态更新。
目标JSON结构
{ "profiles": { "578ed5c5bab24186a6b0f7cd9a952e10": { "name": "as", "type": "custom", "created": "2022-11-02T09:56:53+03:00", "lastUsed": "2022-11-02T09:56:53+03:00" }, "41f62754d535457db1c353872a8aafcf": { "name": "(Default)", "type": "custom", "created": "2022-11-02T09:56:50+03:00", "lastUsed": "2022-11-02T09:56:50+03:00" } }, "selectedProfile": "578ed5c5bab24186a6b0f7cd9a952e10", "settings": { "enableAdvanced": false, "profileSorting": "byName" }, "version": 3 }
方法1:使用JObject直接解析(最灵活)
通过Json.NET的JObject加载JSON,遍历profiles下的所有属性节点,直接提取name值,无需定义任何实体类。
using Newtonsoft.Json.Linq; using System.Collections.Generic; using System.IO; // 读取JSON文件内容 string jsonContent = File.ReadAllText("path-to-your-json-file.json"); JObject jsonRoot = JObject.Parse(jsonContent); // 获取profiles节点 JObject profilesNode = (JObject)jsonRoot["profiles"]; // 收集所有profile的name值 List<string> profileNames = new List<string>(); foreach (JProperty profileProp in profilesNode.Properties()) { // 安全获取name属性,避免空引用 string profileName = profileProp.Value["name"]?.ToString(); if (!string.IsNullOrWhiteSpace(profileName)) { profileNames.Add(profileName); } } // 输出结果 foreach (var name in profileNames) { Console.WriteLine(name); }
方法2:反序列化为Dictionary<string, dynamic>
定义一个极简的根类,将profiles声明为Dictionary<string, dynamic>,既保留类型结构,又支持动态键的遍历。
using Newtonsoft.Json; using System.Collections.Generic; using System.IO; // 仅定义需要的根结构,无需为每个随机键创建类 public class DynamicRoot { public Dictionary<string, dynamic> profiles { get; set; } } // 反序列化JSON string jsonContent = File.ReadAllText("path-to-your-json-file.json"); DynamicRoot root = JsonConvert.DeserializeObject<DynamicRoot>(jsonContent); // 遍历收集name值 List<string> profileNames = new List<string>(); foreach (var profileKvp in root.profiles) { profileNames.Add(profileKvp.Value.name); } // 输出结果 foreach (var name in profileNames) { Console.WriteLine(name); }
方法3:使用ExpandoObject完全动态
将整个JSON反序列化为ExpandoObject,完全摆脱类定义,通过动态类型访问节点。
using Newtonsoft.Json; using System.Dynamic; using System.Collections.Generic; using System.IO; // 反序列化为动态对象 string jsonContent = File.ReadAllText("path-to-your-json-file.json"); dynamic root = JsonConvert.DeserializeObject<ExpandoObject>(jsonContent); // 遍历profiles(需转换为IDictionary访问) List<string> profileNames = new List<string>(); foreach (var profileKvp in (IDictionary<string, object>)root.profiles) { dynamic profile = profileKvp.Value; profileNames.Add(profile.name); } // 输出结果 foreach (var name in profileNames) { Console.WriteLine(name); }
方法对比
- JObject解析:无类依赖,完全适配JSON结构变化,需手动处理空值,适合结构频繁变动的场景。
- Dictionary方法:仅需极简类定义,代码简洁,编译时对根结构有基本检查,平衡灵活性和可读性。
- ExpandoObject:完全动态,零类定义,但编译时无属性检查,易因拼写错误导致运行时异常。
内容的提问来源于stack exchange,提问作者zouFrax
相关产品推荐
相关产品推荐

