KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I have never done much with serialization, but am trying to use Google's gson to serialize a Java object to a file. Here is an example of my issue: 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); } } So this serializes nicely -- but understandably drops the type information on the Animal: {"mDescription":"This is a public exhibit.","mAnimal":{"mName":"Cat","mHabbit":"Playing with yarn"}} This causes real problems for deserialization, though: Exception in thread "main" java.lang.RuntimeException: No-args constructor for interface com.atg.lp.gson.Animal does not exist. Register an
Tags (comma-separated)
Save Edits
Cancel