C#中如何通过可配置路径从动态JSON对象取值?
在C#中通过动态属性路径查询JSON对象的值
以下是几种实用的解决方案,满足你从数据库读取属性路径后,运行时查询JSON动态对象的需求:
方法1:利用Newtonsoft.Json的JObject(推荐)
如果你的动态对象基于Newtonsoft.Json实现,直接转成JObject后使用SelectToken方法就能轻松解析路径:
// 示例JSON字符串(或从动态对象转换) string jsonStr = @"{""Customer"": {""FirstName"": ""John"", ""LastName"": ""Doe""}, ""Address"": {""City"": ""New York""}}"; JObject jsonObj = JObject.Parse(jsonStr); // 从数据库读取的配置路径 string configPath = "Customer.FirstName"; // 查询值 string result = jsonObj.SelectToken(configPath)?.ToString();
如果已经持有ExpandoObject类型的动态对象,也可以直接转成JObject:
dynamic jsonDynamic = GetYourDynamicObject(); JObject jsonObj = JObject.FromObject(jsonDynamic); var result = jsonObj.SelectToken(configPath)?.ToString();
这个方法还支持复杂路径查询,比如数组索引Customer.Orders[1].Amount,无需额外处理。
方法2:使用System.Text.Json的JsonNode(.NET Core 3.0+)
如果项目用的是原生System.Text.Json,可借助JsonNode的SelectToken方法:
using System.Text.Json.Nodes; string jsonStr = @"{""Customer"": {""FirstName"": ""John""}}"; JsonNode jsonNode = JsonNode.Parse(jsonStr); string configPath = "Customer.FirstName"; string result = jsonNode.SelectToken(configPath)?.ToString();
方法3:手动解析路径(自定义实现)
如果不想依赖第三方库,可写一个递归方法解析路径,适配ExpandoObject或普通对象:
public static object GetDynamicValue(object obj, string propertyPath) { string[] pathParts = propertyPath.Split('.'); object currentValue = obj; foreach (string part in pathParts) { if (currentValue is IDictionary<string, object> expandoDict) { if (!expandoDict.TryGetValue(part, out currentValue)) return null; } else { // 处理强类型对象,用反射读取属性 System.Reflection.PropertyInfo prop = currentValue.GetType().GetProperty(part); if (prop == null) return null; currentValue = prop.GetValue(currentValue); } if (currentValue == null) break; } return currentValue; } // 使用示例 dynamic jsonDynamic = GetYourDynamicObject(); string configPath = "Address.City"; string result = GetDynamicValue(jsonDynamic, configPath)?.ToString();
内容的提问来源于stack exchange,提问作者Scott D
相关产品推荐
相关产品推荐

