C# - How to get a property from a JSON string without parsing it to a class using SelectToken and JObject

  • Often you would use a class to represent the JSON object you want to Deserialize. However for whatever reason you might want to skip the class part and select properties using a path. This is popular with XML where you can use xpath to achieve this. You can do the same in C# using JObject and the SelectToken method. We will use following JSON structure:
{
  "quoteSummary": {
    "result": [
      {
        "assetProfile": {
          "address1": "One Apple Park Way",
          "city": "Cupertino",
          "state": "CA",
          "zip": "95014",
          "country": "United States",
          "phone": "408 996 1010",
          "website": "https://www.apple.com",
          "industry": "Consumer Electronics",
          "sector": "Technology"
        }
      }
    ]
  }
}

Using JObject we can get the address using SelectToken:

var data = (JObject)JsonConvert.DeserializeObject(responseBody);
var address = data.SelectToken(
   "quoteSummary.result[0].assetProfile.address1").Value<string>();

In the above we parse the JSON tree using a dot notation and hard brackets for lists [0]. At the end we get the address1 value as a string using .Value<string>().

I hope you found this helpful, let me know in the comments what you think! :)