title: GSON Serialize Polymorphic Object with Type Stored in a Different Object
body: <p>To start off, I have looked at a few other <a href="https://stackoverflow.com/questions/19588020/gson-serialize-a-list-of-polymorphic-objects">answers for similar questions</a>, but they do not answer my particular situation.</p>
  
  <p>I'm parsing JSON messages which consist of a body and a header, where the header stores what type of object the body is:</p>
  
  <pre><code>{
      "body": {
          "eventName": "someEventName"
      },
      "header": {
          "purpose": "event"
      }
  }
  </code></pre>
  
  <p>In Java, I've modeled this structure using the following classes:</p>
  
  <pre><code>public class Message {
      public Body body;
      public Header header;
  }
  
  public class Header {
      public String purpose; // Marks what child class the body of the message uses
  }
  
  public abstract class Body {
      // Child classes store additional fields
  }
  
  // Example implementation of the body class
  public class EventBody extends Body {
      public String eventName; // Name of some event
  }
  </code></pre>
  
  <p>After doing some research, I found that <code>RuntimeTypeAdapterFactory</code> is normally used to parse/write polymorphic objects; however, the <code>RutimeTypeAdapterFactory</code> class relies on the type being stored in the base class of the polymorphic object (i.e. <code>Body</code>). But in this scenario, that's not the case ― the type is stored in another object, <code>Header</code>.</p>
  
  <p>What would be the best way to go about parsing these kind of objects? I'd like to avoid having to write a custom <code>Serializer</code>/<code>Deserializer</code> for compactness, but I wouldn't mind writing them if it's necessary.</p>