java - How to serialize a class with an interface? -
i have never done serialization, trying use google's gson serialize java object file. here example of issue:
public interface animal { public string getname(); } public class cat implements animal { private string mname = "cat"; private string mhabbit = "playing 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 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 serializes nicely -- understandably drops type information on animal:
{"mdescription":"this public exhibit.","manimal":{"mname":"cat","mhabbit":"playing yarn"}}
this causes real problems deserialization, though:
exception in thread "main" java.lang.runtimeexception: no-args constructor interface com.atg.lp.gson.animal not exist. register instancecreator gson type fix problem.
i why happening, having trouble figuring out proper pattern dealing this. did in guide didn't address directly.
put animal transient, not serialized.
or can serialize implementing defaultwriteobject(...) , defaultreadobject(...) (i think thats called...)
edit see part writing instance creator here http://sites.google.com/site/gson/gson-user-guide
gson cant deserialize interface since doesnt know implementing class used, need provide instance creator animal , set default or similar.
Comments
Post a Comment