1

I have a JObject:

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

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

How can I get the value of connectionString and sqlExpression?

I am trying:

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

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

However, I'm not getting the results. Any suggestions?

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
Harshit
  • 397
  • 2
  • 6
  • 17
  • 1
    So you are doing it with Json.Net? You have C# object serialized, so you could just deserialize it and read out the data to your needs from the object. – Marius May 23 '16 at 10:27
  • More answers see [deserializing JSON to .net object using NewtonSoft (or linq to json maybe?)](http://stackoverflow.com/q/4749639) – Michael Freidgeim Jul 22 '16 at 07:57

1 Answers1

3

For this simple JSON structure you can use the SelectToken method navigate to each property value:

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

Fiddle: https://dotnetfiddle.net/00X6kX

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300