bubu uwu
bubu uwu

Reputation: 483

convert byteArray to string to initialize jsonObject

i have byteArray.

is it possible to convert byteArray to String?

please check my code

        byte[] data = **some_byte_array**
        JSONObject jsonObject = new JSONObject(data);

how do i fix this.

Upvotes: 1

Views: 4859

Answers (2)

Bhargav Thanki
Bhargav Thanki

Reputation: 4954

Try this

String decoded = new String(bytes, "UTF-8");

There are a bunch of encodings you can use, look at the Charset class in the Sun javadocs.

The "proper conversion" between byte[] and String is to explicitly state the encoding you want to use. If you start with a byte[] and it does not in fact contain text data, there is no "proper conversion". Strings are for text, byte[] is for binary data, and the only really sensible thing to do is to avoid converting between them unless you absolutely have to.

answer credit goes to https://stackoverflow.com/a/1536365/4211264

Upvotes: 4

Narayan Acharya
Narayan Acharya

Reputation: 1499

Yes you can convert byte array to String using one of the String constructors like this :

String myString = new String(yourByteArray);

Documentation for the same: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#String(byte[])

All the best :)

Upvotes: 0

Related Questions