0

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.

0

1 Answer 1

2

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...
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for your answer! Problem with string conversion solved. What about making int count to be placed on exactly 2 bytes?
@Pandita assuming the byte count is always <= 65535, simply typecast the int to short, or for transmission purposes, use DataOutputStream.writeShort().
I don't think it is that simple. I mean I need to make int count to be uint16 (unsigned integer that is 16 bits large).
@Pandita I know what you want. What I said will work for that
Casting to short didn't work, but I found solution: int count = bytes.length; byte[] data = new byte[2]; data[0] = (byte) (count & 0xFF); data[1] = (byte) ((count >> 8) & 0xFF); Then I send it to ByteArrayOutputStream, concatenate it with msg bytes and use DataOutputStream.write(bytearray) to send whole byte array. Thank you very much!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.