Pandita
Pandita

Reputation: 3

Json/string/byte conversion operations (sending bytes to socket)

I have a problem with converting JSON object to bytes. I need something like:

aJsonObject = new JSONObject();
// ...put somethin
string msg;

msg = aJsonObject.toString();
count = msg.countBytes(); //calculate how many bytes will string `msg` take

THEN I need to convert count to 2-element byte array (actually I need to send 16bit int to socket), convert msg to count-element byte array, link them together and send to TCP socket.

The most compliacted for me is to make count placed on exactly 16 bits.

Exactly same thing I need to do in reverse. Take 2 bytes, make them int, then read int-bytes from socket and eventually convert them to json.

I will be grateful for any help. Thanks in advance.

Upvotes: 0

Views: 1537

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598134

A Java String uses UTF-16 encoding. To convert a String to a byte array, simply call the String.getBytes() method, specifying the desired byte encoding, such as UTF-8. Then read the array's length.

aJsonObject = new JSONObject();
// fill JSON as needed...
String msg = aJsonObject.toString();
byte[] bytes = msg.toBytes(StandardCharsets.UTF_8);
int count = bytes.length;
// use length and bytes as needed...

To reverse the process, simply pass the bytes to the String constructor, specifying the same byte encoding:

bytes[] bytes = ...;
String msg = new String(bytes, StandardCharsets.UTF_8);
// use msg as needed...

Upvotes: 2

Related Questions