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();

3 Answers 3

9

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

   arr = new JSONArray(new String(bArr));
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

So you are telling that i can use this to convert JSONArray to byte array and vice versa?
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();
            }
        }
    }

1 Comment

Please add an explanation with your code. It may help future visitors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.