Here is a good example of base64 encoding byte arrays. It gets more complicated when you throw unicode characters in the mix to send things like PDF documents. After encoding a byte array the encoded string can be used as a JSON property value.

Apache commons offers good utilities:

 byte[] bytes = getByteArr();
 String base64String = Base64.encodeBase64String(bytes);
 byte[] backToBytes = Base64.decodeBase64(base64String);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding

Java server side example:

public String getUnsecureContentBase64(String url)
        throws ClientProtocolException, IOException {

            //getUnsecureContent will generate some byte[]
    byte[] result = getUnsecureContent(url);

            // use apache org.apache.commons.codec.binary.Base64
            // if you're sending back as a http request result you may have to
            // org.apache.commons.httpclient.util.URIUtil.encodeQuery
    return Base64.encodeBase64String(result);
}

JavaScript decode:

//decode URL encoding if encoded before returning result
var uriEncodedString = decodeURIComponent(response);

var byteArr = base64DecToArr(uriEncodedString);

//from mozilla
function b64ToUint6 (nChr) {

  return nChr > 64 && nChr < 91 ?
      nChr - 65
    : nChr > 96 && nChr < 123 ?
      nChr - 71
    : nChr > 47 && nChr < 58 ?
      nChr + 4
    : nChr === 43 ?
      62
    : nChr === 47 ?
      63
    :
      0;

}

function base64DecToArr (sBase64, nBlocksSize) {

  var
    sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length,
    nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2, taBytes = new Uint8Array(nOutLen);

  for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) {
    nMod4 = nInIdx & 3;
    nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4;
    if (nMod4 === 3 || nInLen - nInIdx === 1) {
      for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
        taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255;
      }
      nUint24 = 0;

    }
  }

  return taBytes;
}
Answer from Sam Nunnally on Stack Overflow
Top answer
1 of 6
94

Here is a good example of base64 encoding byte arrays. It gets more complicated when you throw unicode characters in the mix to send things like PDF documents. After encoding a byte array the encoded string can be used as a JSON property value.

Apache commons offers good utilities:

 byte[] bytes = getByteArr();
 String base64String = Base64.encodeBase64String(bytes);
 byte[] backToBytes = Base64.decodeBase64(base64String);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding

Java server side example:

public String getUnsecureContentBase64(String url)
        throws ClientProtocolException, IOException {

            //getUnsecureContent will generate some byte[]
    byte[] result = getUnsecureContent(url);

            // use apache org.apache.commons.codec.binary.Base64
            // if you're sending back as a http request result you may have to
            // org.apache.commons.httpclient.util.URIUtil.encodeQuery
    return Base64.encodeBase64String(result);
}

JavaScript decode:

//decode URL encoding if encoded before returning result
var uriEncodedString = decodeURIComponent(response);

var byteArr = base64DecToArr(uriEncodedString);

//from mozilla
function b64ToUint6 (nChr) {

  return nChr > 64 && nChr < 91 ?
      nChr - 65
    : nChr > 96 && nChr < 123 ?
      nChr - 71
    : nChr > 47 && nChr < 58 ?
      nChr + 4
    : nChr === 43 ?
      62
    : nChr === 47 ?
      63
    :
      0;

}

function base64DecToArr (sBase64, nBlocksSize) {

  var
    sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length,
    nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2, taBytes = new Uint8Array(nOutLen);

  for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) {
    nMod4 = nInIdx & 3;
    nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4;
    if (nMod4 === 3 || nInLen - nInIdx === 1) {
      for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
        taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255;
      }
      nUint24 = 0;

    }
  }

  return taBytes;
}
2 of 6
15

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

You'll have to make this conversion depending on the json parser/generator library you use.

🌐
DevQA
devqa.io › encode-decode-json-byte-array
How to Encode and Decode JSON Byte Array
November 9, 2019 - import javax.xml.bind.DatatypeConverter; public class JsonEncodeDecode { public static void main(String[] args) { String json = "{\"menu\": {\n" + " \"id\": \"file\",\n" + " \"value\": \"File\",\n" + " \"popup\": {\n" + " \"menuitem\": [\n" + " {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"},\n" + " {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"},\n" + " {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}\n" + " ]\n" + " }\n" + "}}"; byte[] bytes = json.getBytes(); String base64Encoded = DatatypeConverter.printBase64Binary(bytes); System.out.println("Encoded Json:\n"); System.out.println(base64Encoded + "\n"); byte[] base64Decoded = DatatypeConverter.parseBase64Binary(base64Encoded); System.out.println("Decoded Json:\n"); System.out.println(new String(base64Decoded)); } }
Discussions

How to receive a byte array inside a JSON
If we take the exact example in this answer, then the binary data is actually only 5 bytes. Representing it as an Array of Uint8 converted to a string encoded as UTF-8, we now have a 23 bytes payload (~336% bigger). The base64 equivalent, (keXYbgM=) even with optional padding is only 8 bytes (~36% bigger than original). 2019-05-27T00:54:41.097Z+00:00 ... Set the byte array value as string. When parsing the JSON ... More on stackoverflow.com
🌐 stackoverflow.com
July 2, 2019
convert JSON Type to Byte array format in java - Stack Overflow
What we see in notepads is String representation of JSON Data, not the actual data. For example if you see an int value 65535 in your notepad, this is actually a string of characters 6,5,5,3 and 5 (five characters = 5*2 bytes = 10 bytes in java) , rather a single int value 65535 (4 bytes in java). More on stackoverflow.com
🌐 stackoverflow.com
java - How do I convert a JSONObject to a byte array and then convert this byte array to get back the original JSONObject? - Stack Overflow
Does anyone know how to do this? I would like to do this because I am using Amazon Kinesis and more specifically the PutRecord API and a PutRecordRequest requires the data to be a ByteBuffer, so I need to convert the JSONObject to a byte array, and then wrap the byte array as a ByteBuffer. More on stackoverflow.com
🌐 stackoverflow.com
September 24, 2020
How do I marshal a JSON array into a map?
Let me see if I understand you correctly: You have a []byte containing a serialized JSON array of unknown contents You want to look at each entry within the serialized array and determine if it is a MyStruct, and if it is store it in a []MyStruct If I understand you correctly, it's actually really simple. json.Unmarshal doesn't fail-fast on error, so you can just create a []MyStruct and unmarshal your data into it, ignoring any errors. Then iterate the results and discard any zero values. Example: https://goplay.tools/snippet/tfgqjnmkbTw More on reddit.com
🌐 r/golang
3
0
December 7, 2023
🌐
Medium
priyarajtt.medium.com › java-program-to-convert-byte-array-to-json-38548b53e27f
Java Program to Convert Byte Array to JSON | by priya raj | Medium
July 12, 2022 - The main important thing in converting byte array to JSON is that the byte array should be of the pattern to get parsed using JsonParser. Now let us see an example for a JsonObject
🌐
Quora
quora.com › How-do-you-pass-a-byte-array-in-a-JSON-request
How to pass a byte array in a JSON request - Quora
Passing a byte array in JSON requires encoding the binary data into a text-safe representation and specifying how the recipient should decode it. Common approaches, examples, and best practices:
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-convert-byte-array-to-json
Java Program to Convert Byte Array to JSON - GeeksforGeeks
June 19, 2022 - The main important thing in converting byte array to JSON is that the byte array should be of the pattern to get parsed using JsonParser. Now let us see an example for a JsonObject
🌐
Coderanch
coderanch.com › t › 422694 › java › ByteArray-JSON
ByteArray in JSON (Web Services forum at Coderanch)
December 24, 2008 - Well, JSON itself does define a standard for arrays, and for number. A byte array is just an array of numbers, so it would look like [1,2,-7,0,42] Using Base64 will be more compact however.
🌐
Baeldung
baeldung.com › home › java › java array › convert byte array to json and vice versa in java
Convert Byte Array to JSON and Vice Versa in Java | Baeldung
April 19, 2024 - @Test void givenJsonString_whenConvertingToByteArrayUsingJackson_thenByteArray() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); byte[] actualByteArray = objectMapper.writeValueAsBytes(jsonString); assertEquals(Arrays.toString(byteArray), Arrays.toString(actualByteArray)); } In this example, we utilize the writeValueAsBytes() method to convert the defined jsonString at the class level to a bytе array.
Find elsewhere
🌐
Webdevtutor
webdevtutor.net › blog › c-sharp-json-byte-array
Working with JSON Byte Arrays in C#
This blog post will guide you through the process of handling JSON byte arrays in C#. using System; using System.Text.Json; byte[] byteArray = { 72, 101, 108, 108, 111 }; // Example byte array string jsonString = JsonSerializer.Serialize(byteArray); Console.WriteLine(jsonString);
🌐
javathinking
javathinking.com › blog › put-byte-array-to-json-and-vice-versa
Can You Put a Byte Array in JSON? How to Convert & Read It Back in Java — javathinking.com
Doing so often leads to encoding ... arrays are incompatible with JSON, the standard solution (Base64 encoding), and step-by-step examples for converting byte arrays to JSON and back....
🌐
GeeksforGeeks
geeksforgeeks.org › javascript-program-to-convert-byte-array-to-json
JavaScript Program to Convert Byte Array to JSON | GeeksforGeeks
July 2, 2024 - Converting a byte array to JSON means transforming a sequence of bytes into a structured JSON format, often involving decoding bytes to a text string and then parsing it into JSON data.
🌐
Liferay
liferay.dev › ask › questions › development › how-to-send-bytes-as-a-json-string-1
How to send Bytes as a JSON string - Liferay.Dev
February 9, 2013 - This Website Uses Cookies · This website uses cookies and similar tools, some of which are provided by third parties (together “tools”). These tools enable us and the third parties to access and record certain user-related and activity data and to track your interactions with this website.
🌐
Liferay
liferay.dev › forums-redirect › - › message_boards › message › 21383243
How to send Bytes as a JSON string - Ask - Liferay
public static void main(String[] args) throws Exception { long folderId = 13713; long groupId = 10179; String scopeGroupId ="10179"; String mimeType = "application/pdf"; long fileEntryTypeId = 0; File file = new File("temp"+"sourceFileName"); String url = "http://localhost:8080/pdfs/ACTANum126.pdf"; System.err.println("URL A conectar" + url); URLConnection conn; try { conn = new URL(url).openConnection(); conn.connect(); InputStream is = conn.getInputStream(); byte[] bytes = IOUtils.toByteArray(is); Base64 base64 = new Base64(); byte[] buffer = new byte[(int) file.length() + 100]; int length =
🌐
.NET Fiddle
dotnetfiddle.net › OJHAYw
Example of sending a byte array through JSON as base-64 | C# Online Compiler | .NET Fiddle
Example of sending a byte array through JSON as base-64 | Test your C# code online with .NET Fiddle code editor.
🌐
GeeksforGeeks
geeksforgeeks.org › convert-a-bytes-array-into-json-format-in-python
Convert a Bytes Array into Json Format in Python - GeeksforGeeks
February 6, 2024 - Below are some of the ways by which we can convert a bytes array into JSON format in Python: ... In this example, we decode the bytes array into a string using 'utf-8' encoding and then parse it as JSON using the json.loads method.
🌐
CodingTechRoom
codingtechroom.com › tutorial › java-java-json-byte-array-conversion
Java JSON Byte Array Conversion: A Comprehensive Guide - CodingTechRoom
A. A byte array is a data structure that allows you to store multiple bytes (0-255 values) in a single variable. It is commonly used for binary data representation. Q. Why would I convert JSON to a byte array?
🌐
JSON for Modern C++
json.nlohmann.me › features › binary_values
Binary Values - JSON for Modern C++
Any binary value will be serialized as byte strings. The library will choose the smallest representation using the length of the byte array. ... // create a binary value of subtype 42 json j; j["binary"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42); // convert to CBOR auto v = json::to_cbor(j);