title: Jackson custom deserialization for polymorphic objects
body: <p>I looked in many questions related to this but i can't find this exact use case.
  Assumption here is that i am using Java Jackson library.</p>
  
  <p>I have the following class hierarchy:</p>
  
  <pre><code>public class Event    {
      @JsonProperty("si")
      String sessionId;
  
      @JsonProperty("eventType")
      String eventType;
  ...
  }
  
  @JsonSerialize(include= JsonSerialize.Inclusion.NON_NULL)
  public class InitEvent extends Event
  {
  
       @JsonProperty("pm")
       Params params;
  
       public Params getParams()
       {
            return params;
       }
  
       .....
  }
  
  @JsonSerialize(include= JsonSerialize.Inclusion.NON_NULL)
  public class RecoEvent extends Event
  {
  
       @JsonProperty("ti")
       String targetId;
  
       @JsonProperty("tt")
       int targetType;
  
  
       public String getTargetId()
       {
             return targetId;
       }
  
      ....
  }
  </code></pre>
  
  <p>The rule of deserialization is:</p>
  
  <ul>
  <li><p>If eventType == 0 then deserialize to a InitEvent</p></li>
  <li><p>If eventType == 0 then deserialize to a RecoEvent </p></li>
  </ul>
  
  <p>Out of the box the Jackson deserialization will not work because it does not know which class to deserialize with. One way to handle that is by doing as follows on the base class:</p>
  
  <pre><code>@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class")
  @JsonSerialize(include= JsonSerialize.Inclusion.NON_NULL)
  public class Event
  </code></pre>
  
  <p>The problem of this solution is assumes the client will serialize with the same mapper since the @class element needs to be present now in the JSON.</p>
  
  <p>My client will not send the extra @class element in the incoming JSON.</p>
  
  <p>What is the required solution?</p>
  
  <p>How I could write a custom deserializer that picks the right derived class based on the eventType value?</p>
  
  <p>Thx in advance </p>