7

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();
Community
  • 1
  • 1
Vithushan
  • 503
  • 3
  • 9
  • 34

3 Answers3

9

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

   arr = new JSONArray(new String(bArr));
blackSmith
  • 3,054
  • 1
  • 20
  • 37
7

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);
Rohit
  • 647
  • 14
  • 30
0
private JsonArray convertByteArrayToJsonArray(byte[] yourByteArray) throws IOException {
        try (ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(yourByteArray))) {
            zipInputStream.getNextEntry();
            try (JsonReader reader = Json.createReader(zipInputStream)) {
                return reader.readArray();
            }
        }
    }