This works but it is horrible - is there a better way?
I have a generic class which in this simple example is as follows
public class MsgWrapper<T> {
@Expose
private T Message;
@Expose
private String Type;
private String uri;
}
Serialising is nasty but trivial e.g.
Type typeToken = new TypeToken<MsgWrapper<Notice>>(){}.getType();
gson.toJson(message,typeToken);
The server receives json which can be either
MsgWrapper<Notice> or MsgWrapper<Alert>
If it is a notice then the 'Type' field will say 'notice' If it is an alert then the 'Type' field will say 'alert'
At the moment I've implemented a custom deserialiser
public MsgWrapper deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject object = json.getAsJsonObject();
if(object.has("Type"))
{
MsgWrapper msgWrapper=new MsgWrapper();
msgWrapper.setType(object.get("Type").getAsString());
if(msgWrapper.getType().equalsIgnoreCase("Notice"))
{
msgWrapper.setMessage(context.deserialize(object.get("Message"), Notice.class));
}
else if(msgWrapper.getType().equalsIgnoreCase("Alert"))
{
msgWrapper.setMessage(context.deserialize(object.get("Message"), Alert.class));
}
return msgWrapper;
}
else
{
throw new JsonParseException("something is wrong...");
}
}
}
This feels deeply clunky and wrong. Is there a better way?