C# - How to parse JSON using DeserializeObject from JSON.net

I recently extended a post on how to call the yahoo finance API with details on how to serialize the returned JSON to an object. I decided to make this post based on it as it might help others who just need to deserialize JSON. As developers we like to convert our JSON to classes so that they are easier to work with and are more "native" in the code that we write. I will use the example from the yahoo API post, but it can be applied to any JSON object.

We will use the following JSON as an example:

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

In order to serialize it to a class we need a class - or for the above several classes. Each class will have to represent a layer (object) in the JSON and together be a representation of the structure. Below I have made these classes starting from QuoteSummaryResponse (the outer unnamed object) to the AssetProfile containing the actual information:

public class QuoteSummaryResponse
{
    public QuoteSummary QuoteSummary { get; set; }
}

public class QuoteSummary
{
    public QuoteSummaryResult[] Result { get; set; }
}

public class QuoteSummaryResult
{
    public AssetProfile AssetProfile { get;set; }
}

public class AssetProfile
{
    public string address1 { get; set; }
    public string city { get; set; }
    public string state { get; set; }
    public string zip { get; set; }
    public string country { get; set; }
    public string phone { get; set; }
    public string website { get; set; }
    public string industry { get; set; }
    public string sector { get; set; }
}

Using the above we can deserialize the JSON into an object using DeserializeObject and get any property, for example the address:

var data = JsonConvert.DeserializeObject<QuoteSummaryResponse>(responseBody);
var address = data.QuoteSummary.Result[0].AssetProfile.address1;

That is all there is to it, you can now work with the JSON as an object. I hope you found this helpful, let me know what you think in the comments down below!