title: Serialize and deserialize a hierarchy of a C# class to Json
body: <p>Is there a way to serialize and then deserialize a class that has a member variable of unknown type that could be either be a simple value type or an instance of the containing class itself ?</p>
  
  <pre><code>public class A
  {
      public dynamic Value { get; set; }//Value could be int or type A for example
  }
  
  public static class ASerializer
  {
      public static string ToJson(A table)
      {
          return JsonConvert.SerializeObject(table);//using Json.Net
      }
  
      public static A FromJson(string json)
      {
          return JsonConvert.DeserializeObject&lt;A&gt;(json);
      }
  }
  
  public class Tests
  {
      public static void TestASerialization()
      {
          var a = new A() { Value = 1 };
          var aa = new A { Value = a };
          var aaa = new A { Value = aa };
          var json = ASerializer.ToJson(aaa);
          var aaa2 = ASerializer.FromJson(json);
  
          var aa2 = (A)aaa2.Value;    //throws
      }
  }
  </code></pre>
  
  <p>if I serialize and then deserialize aaa - I can't cast the Value of the deserialized aaa back to type A I get:</p>
  
  <p>Microsoft.CSharp.RuntimeBinder.RuntimeBinderException : Cannot convert type 'Newtonsoft.Json.Linq.JObject' to 
  'A'</p>
  
  <p>Any suggestions on handling this nested hierarchy elegantly, without resorting to hand coding ?
  Seems to work with just one instance of A with Value of type A.</p>