如何访问Json文件中标记/Parent标记下的密钥?

jecbmhm3  于 2023-04-13  发布在  其他
关注(0)|答案(4)|浏览(107)
{
  "MethodParameters": {
    "operation": [ "write", "click", "text" ],
    "stepDetail": "login",
    "welcome": "Hello Bob!"
  }

如果我想在“MethodParameters”下获取“stepDetail”的值。
我试着这样做:

public static JObject? jsconfig1 = ReadJson(@"DataFiles\jsconfig1.json".ToString()); 

public static string loginA = .SelectToken("MethodParameters").SelectToken("stepDetail").Value<string>();

但对我不起作用。任何帮助都很感激。

nukf8bse

nukf8bse1#

为什么不试试这个

using Newtonsoft.Json;

    json = File.ReadAllText(@"DataFiles\jsconfig1.json");

    var methodParameters = JObject.Parse(json)["MethodParameters"];
    string loginA = (string) methodParameters["stepDetail"];
nlejzf6q

nlejzf6q2#

你的json保存在变量中,你可以访问嵌套的字段。

var json = [YOUR JSON];
var nestedField = json["MethodParameters"]["stepDetail"]);
ctehm74n

ctehm74n3#

为什么你不能做像{nameOfYourObject}.MethodParameters.stepDetail这样的事情?

xfyts7mz

xfyts7mz4#

你应该将你的json转换成一个带有Newtonsoft.Json的对象,然后将它作为任何对象使用。
这应该是你的类:

public class MethodParameters
    {
        public List<string> operation { get; set; }
        public string stepDetail { get; set; }
        public string welcome { get; set; }
    }

    public class Root
    {
        public MethodParameters MethodParameters { get; set; }
    }

相关问题