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 serialising is bad but trivial, eg, The server receives JSO which can either If it notices 'will type' field 'notice' if it is a warning call 'type' field 'alert' At the moment I 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 Instead of using a custom deserializer, so Gson will soon 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
Public Class Messaggraph & lt; T & gt; {@ Apply personalized T-message; Give an example of @ personal string type; Private string uri; }
type type = new TypeToken. & Lt; MsgWrapper & LT; Information & gt; & Gt; () {} GetType () .; Gson.toJson (message, typeToken);
Messaging < Notice & gt; On this message & lt; Alert & gt;
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 ..."); }}}
Maps & lt; String, deserializer & gt;
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.
Comments
Post a Comment