Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple way to convert byte array to JSONArray

I have a byte array which was converted from a JSONArray. Now how to convert it back to JSONArray. Is there any simple lib to do this. Or do i have to use base64 as this post says? Here is the code to convert JSONArray to bytearray:

JSONArray arr = //some value;
byte[] bArr = arr.toString().getBytes();
like image 873
Vithushan Avatar asked Sep 29 '14 11:09

Vithushan


People also ask

How do I create a JsonArray?

A JsonArray object can be created by reading JSON data from an input source or it can be built from scratch using an array builder object. JsonArray value = Json. createArrayBuilder() . add(Json.

How do you convert a byte array into a string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

Can you convert bytes to JSON?

Once you have the bytes as a string, you can use the JSON. dumps method to convert the string object to JSON.

Can we pass byte array in JSON?

JSON does not support that. Use Base64. That is your library supporting it, not JSON itself. The byte array wont be stored as byte array in the JSON, JSON is a text format meant to be human readable.


2 Answers

Since you are not specifying no CharSet on converting the Json array string to bytes. Simply use :

   arr = new JSONArray(new String(bArr));
like image 75
blackSmith Avatar answered Oct 10 '22 09:10

blackSmith


The typical way to send binary in json is to base64 encode it. Java provides different ways to Base64 encode and decode a byte[]. One of these is DatatypeConverter.

Very simply

byte[] originalBytes = new byte[] { 1, 2, 3, 4, 5};
String base64Encoded = DatatypeConverter.printBase64Binary(originalBytes);
byte[] base64Decoded = DatatypeConverter.parseBase64Binary(base64Encoded);
like image 40
Rohit Avatar answered Oct 10 '22 07:10

Rohit