title: Dynamically choosing which class to create object of from json
body: <p>I have an interesting problem that I'm having trouble coming up with a clean solution for.  My application reads collections of json objects that it needs to deserialize to this or that class type based on a field in the json itself.  I have no control over the json structure or how it gets to my application.</p>
  
  <p>I've created models for each type of object that could be coming to the application and I've reached a point where I'm trying to build a service that pulls out the 'type' field and then uses ObjectMapper to deserialize the json to the appropriate Model.</p>
  
  <p>Json example:</p>
  
  <pre><code>{
      "message_type" : "model1"
      "other data" : "other value"
      ...
  }
  </code></pre>
  
  <p>Models:</p>
  
  <pre><code>public class Model1 {
      ...
  }
  
  public class Model2 {
      ...
  }
  </code></pre>
  
  <p>Service?:</p>
  
  <pre><code>public class DynamicMappingService {
  
      public ???? mapJsonToObject(String json) {
          String type = pullTypeFromJson();
  
          ???
      }
  
      private String pullTypeFromJson() {...}
  }
  </code></pre>
  
  <p>I don't want a massive switch statement that says "If type value is this then deserialize to that" but I'm struggling to come up with something clean that does that.  I thought maybe a generic model class where the generic parameter is the Model Type and the only field is the instance of that model type but that doesn't seem right either and I'm not sure what that buys me.  I could also have some sort of empty abstract class that all of the models extend but that seems horrible too.  How do I deal with this?  Extra points for an example.</p>