title: How to serialize a class with an interface?
body: <p>I have never done much with serialization, but am trying to use <a href="http://code.google.com/p/google-gson/" rel="noreferrer">Google's gson</a> to serialize a Java object to a file. Here is an example of my issue:</p>
  
  <pre><code>public interface Animal {
      public String getName();
  }
  
  
   public class Cat implements Animal {
  
      private String mName = "Cat";
      private String mHabbit = "Playing with yarn";
  
      public String getName() {
          return mName;
      }
  
      public void setName(String pName) {
          mName = pName;
      }
  
      public String getHabbit() {
          return mHabbit;
      }
  
      public void setHabbit(String pHabbit) {
          mHabbit = pHabbit;
      }
  
  }
  
  public class Exhibit {
  
      private String mDescription;
      private Animal mAnimal;
  
      public Exhibit() {
          mDescription = "This is a public exhibit.";
      }
  
      public String getDescription() {
          return mDescription;
      }
  
      public void setDescription(String pDescription) {
          mDescription = pDescription;
      }
  
      public Animal getAnimal() {
          return mAnimal;
      }
  
      public void setAnimal(Animal pAnimal) {
          mAnimal = pAnimal;
      }
  
  }
  
  public class GsonTest {
  
  public static void main(String[] argv) {
      Exhibit exhibit = new Exhibit();
      exhibit.setAnimal(new Cat());
      Gson gson = new Gson();
      String jsonString = gson.toJson(exhibit);
      System.out.println(jsonString);
      Exhibit deserializedExhibit = gson.fromJson(jsonString, Exhibit.class);
      System.out.println(deserializedExhibit);
  }
  }
  </code></pre>
  
  <p>So this serializes nicely -- but understandably drops the type information on the Animal:</p>
  
  <pre><code>{"mDescription":"This is a public exhibit.","mAnimal":{"mName":"Cat","mHabbit":"Playing with yarn"}}
  </code></pre>
  
  <p>This causes real problems for deserialization, though:</p>
  
  <pre><code>Exception in thread "main" java.lang.RuntimeException: No-args constructor for interface com.atg.lp.gson.Animal does not exist. Register an InstanceCreator with Gson for this type to fix this problem.
  </code></pre>
  
  <p>I get why this is happening, but am having trouble figuring out the proper pattern for dealing with this. I did look in the <a href="http://sites.google.com/site/gson/gson-user-guide" rel="noreferrer">guide</a> but it didn't address this directly. </p>