如何读取JSON并返回项目值?

问题描述 投票:0回答:1

如何从下面的 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": "Recursion",
        "Available": true
      }
    }
  ]
}
c# json
1个回答
0
投票

正如 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());
    }

请注意,这可能会失败的原因有多种。没有错误处理。

© www.soinside.com 2019 - 2024. All rights reserved.