JSON Polymorphism JSON Polymorphism json json

JSON Polymorphism


JSON objects are just key/value pairs and contain no type information. That means identifying the type of a JSON object automatically isn't possible. You have to implement some logic on the server-side to find out what kind of event you are dealing with.

I would suggest to use a factory method which takes a json string, parses it to find out what kind of Event it is, builds an Event object of the correct subclass and returns it.


You could use Genson library http://code.google.com/p/genson/.It can deserialize to concrete types if the json was produced using Genson. Otherwise you only need to add something like [{"@class":"my.java.class", "the rest of the properties"}...]

// an exampleabstract class Event { String id;}class Click extends Event { double x, y;}// you can define aliases instead of plain class name with package (its a bit nicer and more secure)Genson genson = new Genson.Builder().setWithClassMetadata(true).addAlias("click",            Click.class).create();String json = "[{\"@class\":\"click\", \"id\":\"here\", \"x\":1,\"y\":2}]";// deserialize to an unknown type with a cast warningList<Event> events =  genson.deserialize(json, List.class);// or better define to which generic typeGenericType<List<Event>> eventListType = new GenericType<List<Event>>() {};events = genson.deserialize(json, eventListType);

EDIThere is the wiki example http://code.google.com/p/genson/wiki/GettingStarted#Interface/Abstract_classes_support


Why not using jackson json library ?

It is a full Object/JSON Mapper with data binding functionnality.

It is fast, small footprint, documented, overused, and many others things you will enjoy!