1

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.

bubu uwu
  • 463
  • 2
  • 12
  • 26

2 Answers2

4

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

Community
  • 1
  • 1
Bhargav Thanki
  • 4,924
  • 2
  • 37
  • 43
  • JSON is *almost always* encoded in UTF-8 (see, for example [the RFC](https://datatracker.ietf.org/doc/html/rfc8259#section-8.1)). It's not guaranteed, but it's one of the times where guessing has a pretty good success rate. – Joachim Sauer Aug 25 '21 at 09:32
0

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 :)

Narayan Acharya
  • 1,459
  • 1
  • 18
  • 33