C# 如何读取JSON并返回项的值?

C# 如何读取JSON并返回项的值?,c#,json,C#,Json,如何从下面的JSON文件中读取并获取框架名称(即WinForms)的值 该方法应该是通用的,如果用户提供了一个特定的路径,那么它应该为我获取该值 例如:GetValueFromJson(“Framework/SolveTechnique/Available”)-在本例中,该方法应返回true { "$type": "Config", "Available": true, "AdapterChecksums"

如何从下面的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字符串。调用“反序列化对象”将为您提供一个动态响应。假设始终需要数组的第一个元素,可以执行以下操作:

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

注意:这可能有多种原因导致失败。。没有错误处理。

Framework
是一个数组,如果有多个条目该怎么办?如果您想要用户提供的自定义路径,您可以查看json路径,例如受支持的。@GuruStron-不会有多个条目。如果有多个条目,那么考虑第一个OnthANKS,它是有帮助的。有什么方法可以让我在路径段中包含操作符。在获取路径段的值时,它可以考虑包含什么?在上面的json文件中,在某些情况下它是“AdapterChecksums”,在某些情况下它是“AdapterChecksums-5A98”。但为了概括,我希望将“AdapterChecksums”作为路径段传递。您可以尝试通过执行以下操作来查找当前路径段的名称:
var currPathSegment=((JObject)obj).Children().FirstOrDefault(c=>pathSegments[0]。Contains(c.path))?.path??路径段[0]获取空值。