title: Deserializing JSON based on object type
body: <p>I am creating a service that receives requests in the form of JSON messages. I need to parse the message and take the appropriate action based on the request type. For example (in pseudo code):</p>
  
  <pre><code>switch(request.type) {
      case "NewOrder":
          createNewOrder(order);
          break;
      case "CancelOrder"
          cancelOrder(orderId);
          break;
  }
  </code></pre>
  
  <p>It seems that most JSON APIs (at least those that do the object mapping for you) need the root object type to deserialize. Is there any elegant way around this?</p>
  
  <p>As an example, in the Jackson API (using full object mapping), I need to call the mapper as follows:</p>
  
  <pre><code>NewOrder newOrder = mapper.readValue(src, NewOrder.class);
  CancelOrder cancelOrder = mapper.readValue(src. CancelOrder.class);
  </code></pre>
  
  <p>Which means that I need to know the object's class even before I have parsed it. What I really need is some way to peek into the JSON string, determine the request type and then call the appropriate readValue() method - something like this:</p>
  
  <pre><code>String requestType = getRequestType(src);
  switch(request.type) {
      case "NewOrder":
          NewOrder newOrder = mapper.readValue(src, NewOrder.class);
          createNewOrder(newOrder.order);
          break;
      case "CancelOrder"
          CancelOrder cancelOrder = mapper.readValue(src. CancelOrder.class);
          cancelOrder(cancelOrder.orderId);
          break;
  }
  </code></pre>
  
  <p>Is it possible to do this using Jackson or any other Java JSON parser? I am sure I can go to a lower level and use a streaming API or a node based API, but trying to avoid that complexity if I can.</p>