C# - How to get a list from a JSON string using SelectToken without having to parse the whole structure

Often when working with JSON you would parse it to a C# object structure that matches your JSON. But sometimes you may want only a subset of it or have other reasons for not parsing it to an object, in this context you can use SelectToken from the Newtonsoft Json package. If we have the 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"

We can get the contents of the result array using the below code:

var jsonObj = (JObject)JsonConvert.DeserializeObject(json);
var jsonResult = jsonObj.SelectToken("quoteSummary.result");

This will return each object in the array as a JToken. You can run a select statement on the list to map it to a different format, in the below we map it to strings:

var jsonResult = jsonObj.SelectToken("quoteSummary.result")
   .Select(x => x.Value<string>());

You can also select a specific string within the nested object structure of the list using SelectToken and a wildcard *for the list index:

var jsonResult = jsonObj.SelectTokens("quoteSummary.result[*].assetProfile.city")

This will give you the string Cupertino in a list.

Feel free to also check out my post on how to use selectToken to get a single property from json. That was a few examples, I hope you found them useful, please let me know in the comments if you did!