如何使用Dictionary对象导航含嵌套对象的JSON?
可行,两种实用实现方案供你选择
方案一:基于已有的Dictionary<string, object>实现路径遍历
既然已经将JSON反序列化为Dictionary<string, object>,可以写一个扩展方法,通过拆分路径段逐层遍历嵌套字典:
using System.Collections.Generic; public static class DictionaryPathHelper { public static object GetNestedValue(this Dictionary<string, object> rootDict, string path) { if (rootDict == null || string.IsNullOrWhiteSpace(path)) return null; object currentNode = rootDict; var pathSegments = path.Split('.'); foreach (var segment in pathSegments) { if (currentNode is not Dictionary<string, object> currentDict) return null; // 当前节点不是字典,无法继续查找 if (!currentDict.TryGetValue(segment, out currentNode)) return null; // 找不到对应路径段的键 } return currentNode; } }
用法示例:
// 假设你已经有反序列化后的values字典 var temperatureObj = values.GetNestedValue("attributes.temperature"); // 强转成目标类型(比如double) if (temperatureObj is double temperature) { Console.WriteLine($"温度:{temperature}"); } var pressureObj = values.GetNestedValue("attributes.pressure"); if (pressureObj is int pressure) { Console.WriteLine($"压力:{pressure}"); }
如果需要在路径不存在时抛出异常,只需把返回null的地方改成抛出KeyNotFoundException即可。
方案二:直接用JObject内置的路径查询(更简洁高效)
Newtonsoft.Json的JObject本身就支持路径查询,无需手动遍历字典,还支持数组索引等复杂路径:
using Newtonsoft.Json.Linq; // 直接解析JSON字符串为JObject(无需先转Dictionary) var jObj = JObject.Parse(json); // 用SelectToken查询路径,支持.分隔的嵌套键,甚至数组索引比如"attributes.readings[0].value" var temperature = jObj.SelectToken("attributes.temperature")?.Value<double>(); var pressure = jObj.SelectToken("attributes.pressure")?.Value<int>();
如果已经持有Dictionary<string, object>,也可以将其转换为JObject再查询:
var jObj = JObject.FromObject(values); var temperature = jObj.SelectToken("attributes.temperature")?.Value<double>();
注意事项
- 两种方案均支持任意深度的嵌套路径
- 如果键名包含
.等特殊字符,方案一需要调整拆分逻辑,方案二可以用引号包裹键名,比如"attributes.\"temp.value\"" - 路径不存在时,两种方案都会返回
null,可根据业务需求改为返回默认值或抛出异常
内容的提问来源于stack exchange,提问作者cperry
相关产品推荐
相关产品推荐

