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();
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.
There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.
Once you have the bytes as a string, you can use the JSON. dumps method to convert the string object to 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.
Since you are not specifying no CharSet
on converting the Json array string to bytes. Simply use :
arr = new JSONArray(new String(bArr));
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With