title: Deserializing a nested object in JSON to a specific type
body: <p>I have a class on the C# end that looks something like this:</p>
  
  <pre><code>[DataContract]
  public class MyObject
  {
      [DataMember]
      public SomeEnum FooType { get; set; }
  
      [DataMember]
      public FooBase MyFoo { get; set; }
  }
  </code></pre>
  
  <p>Where, basically, the value in the property <code>FooType</code> should tell you what specific type derived from <code>FooBase</code> is present in the property <code>MyFoo</code>.</p>
  
  <p>Now if I just wanted to deserialize a object derived from <code>FooBase</code> I could just do something like:</p>
  
  <pre><code>var myFoo = JsonConvert.DeserializeObject(myJsonString, typeof(FooDerived)) as FooDerived;
  </code></pre>
  
  <p>But how do I deserialize a <code>MyObject</code> where the <code>FooBase</code> object is nested and the information about what type it is can only be determined by partially deserializing the object first? </p>
  
  <p>I'm thinking this is going to need a custom converter derived from JsonConverter, but I'm not entirely sure how to make <code>ReadJson</code> work here.</p>
  
  <p>Something like this?</p>
  
  <pre><code>public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  {
      var result = new MyObject();
      while(reader.Read())
      {
          if(reader.TokenType == JsonToken.PropertyName)
          {
             var prop = reader.Value as string;
             if (prop == "FooType")
             {
                 reader.Read();
                 result.FooType = (SomeEnum)reader.ReadAsInt32();   // or something like that
             }
             if (prop == "MyFoo")
             {
                 reader.Read();
                 // now the reader.TokenType should be StartObject, but I can't
                 // deserialize the object because I don't know what type it is
                 // I might not have read "FooType" yet 
                 // So I really need to pull this whole sub object out as a string
                 // and deserialize it later???
             }
          }
      }
      return result;
  }
  </code></pre>