1

I am trying to read and write JSON directly to and from a socket stream using the gson library.

I have a base class that all messages are derived from:

abstract class MessageBase
{
    public String type = this.getClass().toString();
}

An example would be:

class RequestMessage extends MessageBase
{
    public String request = "my request";
}

What I wish to do is have the following methods:

MessageBase readMessage(Reader reader);
void writeMessage(Writer writer, MessageBase message);

Where they read and write directly from the stream.

This will allow me to call something like:

writeMessage(myWriter, (MessageBase) (new RequestMessage()))

or

MessageBase message = readMessage(myReader);

if (message instance of RequestMessage)
{
    RequestMessage request = (RequestMessage) message;

    // do something here
}

I hope it makes sense what I am hoping to achieve, is it even possible?

Any input would be greatly appreciated. Thanks

Cheetah
  • 13,785
  • 31
  • 106
  • 190
  • Sure its possible. What problems are you having with the implementation? – Perception May 17 '13 at 11:56
  • I don't have an implementation. Currently I send the JSON message down the pipe prefixed with the message length. Read the whole message into a string and deserialize using `Gson.fromJson()` but I need to know the type beforehand. – Cheetah May 17 '13 at 12:03
  • Well, Gson can already ready from streams directly (aka, you don't need to send the message length in the stream). And you can handle polymorphic serialization/deserialization with a type adapter. As described [here](http://stackoverflow.com/questions/5800433/polymorphism-with-gson). – Perception May 17 '13 at 12:55
  • @Perception thank you that link helped me solve the problem. What is the protocol here. Perception has answered my question? – Cheetah May 17 '13 at 14:00
  • Perception should post his comment as an answer and you accept it. – Kevin May 17 '13 at 14:20
  • @Ben - post your final solution as an answer, then accept it. So anybody who runs into this in the future can use it. – Perception May 17 '13 at 15:12

0 Answers0