title: Deserializing heterogenous JSON array into covariant List<> using Json.NET
body: <p>I have a JSON-array containing objects of different types with different properties. One of the properties is called "type" and determines the type of the array item. Here is an example of my data:</p>
  
  <pre><code>   [{
          type : "comment",
          text : "xxxx"
      }, {
          type : "code",
          tokens : [{
                  type : "ref",
                  data : "m"
              }, {
                  type : "operator",
                  data : "e"
              }
          ]
      }, {
          type : "for",
          boundLocal : {
              type : "local",
              name : "i",
              kind : "Number"
          },
          upperBound : {
              type : "ref",
              tokens : [{
                      type : "operator",
                      data : "3"
                  }, {
                      type : "operator",
                      data : "0"
                  }
              ]
          },
          body : [{
                  type : "code",
                  tokens : [{
                          type : "ref",
                          data : "x"
                      }
                  ]
              }, {
                  type : "code",
                  tokens : [{
                          type : "ref",
                          data : "y"
                      }
                  }
                  ]
          ]
      ]
  </code></pre>
  
  <p>To map those objects to my .Net implementation I define a set of classes: one base class and several child classes (with a complex hierarchy, having 4 "generations"). Here is just a small example of these classes:</p>
  
  <pre><code>public abstract class TExpression
  {
      [JsonProperty("type")]
      public string Type { get; set; }
  }
  
  public class TComment : TExpression
  {
      [JsonProperty("text")]
      public string Text { get; set; }
  }   
  
  public class TTokenSequence : TExpression
  {
      [JsonProperty("tokens")]
      public List&lt;TToken&gt; Tokens { get; set; }
  }
  </code></pre>
  
  <p>What I want to reach is to be able to deserialize this array into a covariant generic list, declared as:</p>
  
  <pre><code>List&lt;TExpression&gt; myexpressions = JsonConvert.DeserializeObject&lt;List&lt;TExpression&gt;&gt;(aststring);
  </code></pre>
  
  <p>This list should contain the instances of appropriate child classes inheriting from TExpression, so I can use the following code later in my code:</p>
  
  <pre><code>foreach(TExpression t in myexpressions)
  {
      if (t is TComment) dosomething;
      if (t is TTokenSequence) dosomethingelse;
  }
  </code></pre>
  
  <p>How can I reach it using JSON.NET?</p>