Adam Sznajder
Adam Sznajder

Reputation: 9216

Receive JSON without '\0'

I have to integrate my application with an existing (not modifiable) Python script which sends the JSON messages without '\0' or any other "end-of-message" character. Is there any better way to handle incoming messages that just to read data from the socket byte after byte and count brackets? In this application sending { or } in message content is illegal due to the protocol so this code works fine but seems to me ugly:

  int i = 0;
  int brackets = 0;
  byte[] msg = new byte[4096];
  do
  {
       byte chunk = reader.readByte();
       msg[i++] = chunk;
       if (chunk == 123)  // check if '{'
           brackets++;
       else if (chunk == 125) // check if '}'
           brackets--;
  } while ( brackets > 0);
  byte[] finalMsg = Arrays.copyOfRange(msg, 0, i);

EDIT Python code:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((server_ip, server_port))
logging.info('Connected to: %s', (server_ip, server_port))
s.send(json.dumps(data))
logging.info('Sent message: %s', json.dumps(data))

I analyse text using bytes because this script sends each character as a single byte and as far as I know char is 2 bytes long in Java. When I tried to receive data char-after-char I was not able to compare them with { and }.

Upvotes: 2

Views: 150

Answers (1)

Timofey Gorshkov
Timofey Gorshkov

Reputation: 5125

You coud use Gson library:

Gson gson = new Gson();
JsonReader jr = new JsonReader(reader);
String msg1 = gson.toJson(gson.fromJson(jr, Object.class));
String msg2 = gson.toJson(gson.fromJson(jr, Object.class));
...

Where reader is input stream from socket reader.

Upvotes: 1

Related Questions