如何在json.net中访问子值

时间:2016-10-13 06:35:05

标签: c# 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"}}

现在,如果我尝试使用

获取Child“o2”
  

Console.WriteLine(_json [ “SAMPLE_DATA”] [ “O2”]);

我收到以下错误消息

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"}

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

2 个答案:

答案 0 :(得分:5)

正如您的样本jsondata中存储的值sample_datavar _json = JObject.Parse(jsondata.ToString()); var sampledataJson = JObject.Parse(_json["sample_data"].ToString()); Console.WriteLine(sampledataJson["o2"]); 字符串。

试试这个

   select table_order.*, table_user.name AS order_name, table_user.name AS taker_name FROM 
            table_user 
            INNER JOIN table_order ON   table_order.id_user_order = table_user.id_user
            INNER JOIN table_order ON   table_order.id_user_taker = table_user.id_user 

答案 1 :(得分:1)

你可以使用动态做到这一点。

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