如何从嵌套的JObject获取特定属性的值

时间:2016-05-23 10:24:53

标签: c# json json.net

我有一个JObject:

{
  "config": {
    "DataSource": {
      "connectionString": "Localserver",

      "sqlExpression": "select id As 'key', logHeader As 'Label' from Log"
    }
  }
}

如何获得connectionStringsqlExpression的价值?

我在尝试:

JObject result = new JObject(
             data["DataSource"]
             .SelectMany(jt => jt["properties"]));

string connectionString = result.GetValue("connectionString").ToString();
string sqlExpression = result.GetValue("sqlExpression").ToString();

但是,我没有得到结果。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

对于这个简单的JSON结构,您可以使用SelectToken方法导航到每个属性值:

JObject result = JObject.Parse(json);
string connectionString = (string)result.SelectToken("config.DataSource.connectionString");
string sqlExpression = (string)result.SelectToken("config.DataSource.sqlExpression");

小提琴:https://dotnetfiddle.net/00X6kX