gson - Deserialising a generic with unknown compile time type where a field indicates the type -


This works but it's awesome - is there a better way?

I have a general category that is in this simple example as follows

  Public Class Messaggraph & lt; T & gt; {@ Apply personalized T-message; Give an example of @ personal string type; Private string uri; }   

serialising is bad but trivial, eg,

  type type = new TypeToken. & Lt; MsgWrapper & LT; Information & gt; & Gt; () {} GetType () .; Gson.toJson (message, typeToken);   

The server receives JSO which can either

  Messaging < Notice & gt; On this message & lt; Alert & gt;   

If it notices 'will type' field 'notice' if it is a warning call 'type' field 'alert'

At the moment I

  public MsgWrapper deserialize (JsonElement json, type typeOfT, JsonDeserializationContext context) throws JsonParseException {JSONObject object = json.getAsJsonObject () is executing a custom Deserialiser; If (object.has ("type")) {messagegrapper msgWrapper = new msgwrapper (); MsgWrapper.setType (object.get ("type") getAsString ().); If (MsgWrapperkgetType (). Equals ignore CAS ( "Notice")) {msgWrapper.setMessage (context.deserialize (object.get ( "message"), notice. Square)); } Else if (msgWrapper.getType () equalsIgnoreCase ( "Warning").) {MsgWrapper.setMessage (context.deserialize (object.get ( "message"), Alert.class)); } Return msgWrapper; } And (new) JsonParseException ("Something is wrong ..."); }}}   

Does this feel a mess and mess is there any better way?

The solution that you have posted is as good as the least as good as the current Gson release is regarded as polymorphic assertion.

You can apply the suggestions with the custom deserializer some small changes to external configuration, refer to the change donations to use as along the lines Maps & lt; String, deserializer & gt;

Instead of using a custom deserializer, so Gson will soon look for RuntimeTypeAdapter Simple polymorphic deserialization. See for more information, even if you can not use the RuntimeTypeAdapter , it provides at least one instance to create a configuration custom deserializer.

JSON mapping can switch APIs, so I recommend to consider Jackson, as there is a work and relatively simple polysulfin deserializer system available in it. I posted a few simple examples

Comments

Popular posts from this blog

qt - switch/case statement in C++ with a QString type -

python - sqlite3.OperationalError: near "REFERENCES": syntax error - foreign key creating -

Python's equivalent for Ruby's define_method? -