如何访问json.net中的子值



我正在尝试解析json以访问子值。下面是json示例,

jsondata = {
  "sample_data": "{"o2:{"testname":"o2","department":"chemistry","normalvalue":"l","testmethod":"j","specimen":"g","referelprice":"y","normalprice":"i","discountprice":"o"}}"
}
下面是我的代码
var _json = JObject.Parse(jsondata.ToString());
Console.WriteLine(_json["sample_data"]);

这段代码给出了输出

{"o2":{"testname":"o2","department":"chemistry","normalvalue":"l","testmethod":"j","specimen":"g","referelprice":"y","normalprice":"i","discountprice":"o"}}

现在如果我试图通过使用

获取子元素"o2"

Console.WriteLine (_json [" sample_data "]["氧气"]);

i am getting below error message

cannot access child value on newtonsoft.json.linq.jvalue

请帮助我如何获得子值。我希望输出像

{"testname":"o2","department":"chemistry","normalvalue":"l","testmethod":"j","specimen":"g","referelprice":"y","normalprice":"i","discountprice":"o"}

我怎样才能做到这一点。请帮助。

在您的示例中,jsondata对应sample_data的值是字符串。

试试这个

var _json = JObject.Parse(jsondata.ToString());
var sampledataJson = JObject.Parse(_json["sample_data"].ToString());
Console.WriteLine(sampledataJson["o2"]);

可以使用dynamic。

dynamic a = JsonConvert.DeserializeObject(yourJson);
Console.WriteLine(a.sample_data.o2.ToString());

相关内容

  • 没有找到相关文章