I am working on some server code, where the client sends requests in form of JSON. My problem is, there are a number of possible requests, all varying in small implementatio
Genson library provides support for polymorphic types by default. Here is how it would work:
// tell genson to enable polymorphic types support
Genson genson = new Genson.Builder().setWithClassMetadata(true).create();
// json value will be {"@class":"mypackage.LoginRequest", ... other properties ...}
String json = genson.serialize(someRequest);
// the value of @class property will be used to detect that the concrete type is LoginRequest
Request request = genson.deserialize(json, Request.class);
You can also use aliases for your types.
// a better way to achieve the same thing would be to use an alias
// no need to use setWithClassMetadata(true) as when you add an alias Genson
// will automatically enable the class metadata mechanism
genson = new Genson.Builder().addAlias("loginRequest", LoginRequest.class).create();
// output is {"@class":"loginRequest", ... other properties ...}
genson.serialize(someRequest);