title: How to Dynamically convert JSON to right DTO class?
body: <p>I have JSON data which I want to convert to correct type and then handle it. I'm using MONO and NewtonSoft's JSON library. I.E. JSON and object must match properties 1:1 to convert to right DTO. DTO's have unique properties always.</p>
  
  <p>Both Activator.CreateInstance() and Convert.ChangeType() doesn't seem to compile.</p>
  
  <p>DTOs:</p>
  
  <pre><code>class JSONDTO
  {
  
  }
  
  class JSONCommandDTO : JSONDTO
  {
      public string cmd;
  }
  
  class JSONProfileDTO : JSONDTO
  {
      public string nick;
      public string name;
      public string email;
  }
  
  class JSONMessageDTO : JSONDTO
  {
      public string msg;
  }
  </code></pre>
  
  <p>Server:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Threading;
  using Newtonsoft.Json;
  
  class Server
  {
      protected static List&lt;JSONDTO&gt; DTOList; 
  
      static void Main()
      {
          DTOList = new List&lt;JSONDTO&gt;();
  
          DTOList.Add(new JSONProfileDTO());
          DTOList.Add(new JSONCommandDTO());
          DTOList.Add(new JSONMessageDTO());
  
          // ...
  
      }
  
      protected static void OnMessage (string message)
      {
          dynamic rawObject;
  
          try
          {
              // Or try to convert to right DTO here somehow?
              rawObject = JsonConvert.DeserializeObject&lt;dynamic&gt;(message);
          } catch (JsonReaderException ex) {
              // Invalid JSON
              return;
          }
  
          int dtoCount = DTOList.ToArray().Length;
          int errCount = 0;
  
          JSONDTO DTOObject;
  
          foreach (var dto in DTOList.ToList()) {
              try {
                  // Doesn't compile:
  
                  // DTOObject = Activator.CreateInstance(dto.GetType(), rawObject);
                  // DTOObject = Convert.ChangeType(rawObject, dto.GetType());
                  break; // Match found!
              } catch (Exception ex) {
                  // Didn't match
                  errCount++;
              }
          }
  
          if (errCount == dtoCount) {
              // Right DTO was not found
              return;
          }
  
  
          if (DTOObject is JSONProfileDTO) {
              AssignProfile((JSONProfileDTO) DTOObject);
          }
          else if (DTOObject is JSONCommandDTO)
          {
              RunCommand((JSONCommandDTO) DTOObject);
          }
          // etc ..
  
      }
  
      protected static void RunCommand (JSONCommandDTO command)
      {
          string cmd = command.cmd;
  
          Console.WriteLine("command == " + cmd);
      }
  
      protected static void AssignProfile(JSONProfileDTO profile)
      {
          Console.WriteLine("got profile!");
      }
  
  }
  </code></pre>
  
  <p>}</p>