Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 25th, 2012  |  syntax: None  |  size: 1.19 KB  |  hits: 8  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Deserialising a generic with unknown compile time type where a field indicates the type
  2. public class MsgWrapper<T> {
  3. @Expose
  4. private T Message;
  5. @Expose
  6. private String Type;
  7. private String uri;
  8. }
  9.        
  10. Type typeToken = new TypeToken<MsgWrapper<Notice>>(){}.getType();
  11. gson.toJson(message,typeToken);
  12.        
  13. MsgWrapper<Notice> or MsgWrapper<Alert>
  14.        
  15. public MsgWrapper deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
  16.         JsonObject object = json.getAsJsonObject();
  17.         if(object.has("Type"))
  18.         {
  19.             MsgWrapper msgWrapper=new MsgWrapper();
  20.             msgWrapper.setType(object.get("Type").getAsString());
  21.             if(msgWrapper.getType().equalsIgnoreCase("Notice"))
  22.             {
  23.              msgWrapper.setMessage(context.deserialize(object.get("Message"), Notice.class));
  24.             }
  25.             else if(msgWrapper.getType().equalsIgnoreCase("Alert"))
  26.             {
  27.              msgWrapper.setMessage(context.deserialize(object.get("Message"), Alert.class));  
  28.             }
  29.             return msgWrapper;
  30.         }
  31.         else
  32.         {
  33.             throw new JsonParseException("something is wrong...");
  34.         }
  35.     }
  36. }