Easy way to convert byte array to JSONArray

I have a byte array that has been converted from JSONArray. Now how to convert it back to JSONArray. Is there a simple lib for this. Or do I need to use base64 as this message? Here is the code for converting JSONArray to bytearray:

JSONArray arr = //some value; byte[] bArr = arr.toString().getBytes(); 
+6
source share
2 answers

Since you are not specifying no CharSet to convert a Json array string to bytes. Just use:

  arr = new JSONArray(new String(bArr)); 
+8
source

A typical way to send binary to json is with base64 encoding. Java provides various methods for encoding Base64 and decoding a byte []. One of them is DatatypeConverter.

Very simple

 byte[] originalBytes = new byte[] { 1, 2, 3, 4, 5}; String base64Encoded = DatatypeConverter.printBase64Binary(originalBytes); byte[] base64Decoded = DatatypeConverter.parseBase64Binary(base64Encoded); 
+7
source

Source: https://habr.com/ru/post/976000/


All Articles