Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is an answer I came to:</p> <p>First of all I have switched from <a href="http://jackson.codehaus.org/1.0.0/javadoc/org/codehaus/jackson/map/ObjectMapper.html" rel="nofollow noreferrer">ObjectMapper</a> to <a href="http://sites.google.com/site/gson/gson-user-guide" rel="nofollow noreferrer">Gson</a>. Define an abstract class and an enum of types:</p> <pre><code>public abstract class Message { private MessageType type; protected Message(){ type = setType(); } protected abstract MessageType setType(); public MessageType getType() { return type; } public void setType(MessageType type) { this.type = type; } } public enum MessageType { PRESENCE(PresenceMessage.class), TEXT(TextMessage.class); private Class&lt;? extends Message&gt; clazz; private MessageType(Class&lt;? extends Message&gt; clazz){ this.clazz = clazz; } public Class&lt;? extends Message&gt; getClazz() { return clazz; } } </code></pre> <p>Every class that extends the Message is the actual one we are sending over Json. It has to implement the getType() method.</p> <p>So when desirializing just use that code :</p> <pre><code> String line; BufferedReader reader = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream(),"UTF-8")); while ((line = reader.readLine()) != null){ builder.append(line); } if (clazz == Message.class){ String string = builder.toString(); Message message = gson.fromJson(string,Message.class); if (message.getType() == null) throw new IllegalStateException("Could not de-serialize message " + builder.toString() ); return (T)gson.fromJson(string,message.getType().getClazz()); } </code></pre> <p>I hope you can fill the missing parts by yourself.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload