c# - 如何读取 JSON 并返回项目的值?
问题描述
如何从下面的 JSON 文件中读取并获取框架名称(即 WinForms)的值。
该方法应该是通用的,这样如果用户提供特定的路径,那么它应该为我提供价值。
例如:GetValueFromJson("Framework/SolveTechnique/Available")
- 在这种情况下,该方法应该返回 true
{
"$type": "Config",
"Available": true,
"AdapterChecksums": {
"$type": "UserList`2"
},
"Identification": true,
"Verification": false,
"Framework": [
{
"$type": "custom",
"Name": "WinForms",
"Technique": {
"$type": "Technique",
"PropertyName": "Name",
"Available": true
},
"SolveTechnique": {
"$type": "Userdefined",
"Available": true
},
"AITechnique": {
"$type": "AI",
"X_Value": 2,
"Y_Value": 3,
"Available": true
},
"WaitTechnique": {
"$type": "Recurssion",
"Available": true
}
}
]
}
解决方案
正如 Guru Stron 提到的,您可以使用 Newtonsoft Json 来解析您的 json 字符串。调用“DeserializeObject”会给你一个动态。假设您总是想要数组的第一个元素,您可以执行以下操作:
public object GetValueByQuery(string jsonString, string queryString)
{
dynamic obj = JsonConvert.DeserializeObject(jsonString);
var pathSegments = queryString.Split("/");
return GetValue(obj, pathSegments);
}
private object GetValue(dynamic obj, string[] pathSegments)
{
if (obj is Newtonsoft.Json.Linq.JArray)
{
return GetValue(obj[0], pathSegments);
}
var currPathSegment = ((JObject)obj).Children().FirstOrDefault(c => pathSegments[0].Contains(c.Path))?.Path ?? pathSegments[0];
if (pathSegments.Length == 1)
{
return obj[currPathSegment];
}
return GetValue(obj[currPathSegment], pathSegments.Skip(1).ToArray());
}
请注意,这可能失败的原因有多种。没有错误处理。
推荐阅读
- altair - 在另存为 html 的 altair 图表中使用 width="container"
- python - Python中的正则表达式替换
- pandas - 熊猫应用功能无法解决
- python - 使用 Python/Pyspark 在 Salesforce 中查询具有 400 万条记录和 250 列的表
- c# - 手动优化 efcore 生成的 SQL
- facebook - check_batch_request_status 仅响应 5 个产品错误
- javascript - Thingsboard 仪表板自定义操作 NullInjectorError
- python - Python - 从方法回调到另一个类
- c - 在 C 中的 2 个线程中运行函数的问题
- angular - 将“根”服务注入模块服务