首页 > 解决方案 > 如何读取 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
      }
    }
  ]
}

标签: c#json

解决方案


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

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


推荐阅读