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.

🌐
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
🌐
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)); } }
🌐
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.
🌐
GitHub
github.com › imjuni › json-byte
GitHub - imjuni/json-byte: json-byte · GitHub
JSON Byte is a tool that visualizes the structure of your JSON or YAML data as an intuitive graph view.
Starred by 55 users
Forked by 3 users
Languages: TypeScript 93.0% | JavaScript 3.4% | CSS 2.7% | HTML 0.9%
🌐
Go by Example
gobyexample.com › json
Go by Example: JSON
Go offers built-in support for JSON encoding and decoding, including to and from built-in and custom data types · We’ll use these two structs to demonstrate encoding and decoding of custom types below
🌐
TutorialsPoint
tutorialspoint.com › article › How-can-I-convert-a-bytes-array-into-JSON-format-in-Python
How can I convert a bytes array into JSON format in Python?
March 5, 2020 - my_str = b'{"foo": 42}' # b means its a byte string new_str = my_str.decode('utf-8') # Decode using the utf-8 encoding import json d = json.dumps(my_str) print(d)
🌐
Readthedocs
universal-binary-json.readthedocs.io › en › latest › spec.html
Specification — Universal Binary JSON 0.9-dev documentation
Let’s look at another example, ... look like this (whitespace added for readability): [a][6] - 2 bytes [Z] - 1 byte [T] - 1 byte [F] - 1 byte [I][4782345193] - 5 bytes [D][153.132417549] - 9 bytes [s][3][ham] - 5 bytes...
Find elsewhere
🌐
Ubjson
ubjson.org › type-reference › value-types
Value Types – Universal Binary JSON Specification
The same string in Russian is “привет” with a byte length of 12 and in Arabic the text becomes “مرحبا” with a byte length of 10. Here are some examples of what different string values look like to illustrate the point:
🌐
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
🌐
Liferay
liferay.dev › forums-redirect › - › message_boards › message › 21383243
How to send Bytes as a JSON string - Ask - Liferay
as String sTRBytes = JsonWriter.objectToJson(bytes); returns {"@type":"B","@items”:[23,34,35,12…..]} you just have to take off what is not need sTRBytes = sTRBytes.substring(24,sTRBytes.length()-2); (or any other way to get the content of a Byte[] as a string of a list of numbers) then ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-parse-json-from-bytes-in-python
How to Parse Json from Bytes in Python - GeeksforGeeks
July 23, 2025 - By decoding the bytes with the appropriate encoding (utf-16 in this case) to obtain a string (decoded_data_utf16), we then use json.loads to parse the JSON string into a Python dictionary (parsed_json_utf16). Subsequently, specific values such as name, age, and city are accessed from the parsed JSON with UTF-16 encoding, and these values are printed to the console. ... import json # Example JSON data with bytes encoded using different encodings json_data_utf16 = b'\xff\xfe{\x00&quot;\x00n\x00a\x00m\x00e\x00&quot;\x00:\x00 \x00&quot;\x00A\x00n\x00i\x00l\x00&quot;\x00,\x00 \x00&quot;\x00a\x00g\x
🌐
Dot Net Perls
dotnetperls.com › json-go
Go - JSON Example: Marshal, Unmarshal - Dot Net Perls
February 18, 2023 - Continuing on, we convert a Go struct into JSON data. We have a type Box, which is a custom struct. It has 4 fields—a Width, Height, Color and a bool called Open. Start We create an instance of our Box type. We specify its Width, Height, Color and its Open value. Info Marshal receives an object instance. We pass it our Box instance and it converts it to a byte slice of the encoded data.
🌐
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
JSON is a text format encoded in ... may include sequences that are invalid in UTF-8. For example, a byte array with the value 0xC3 0x28 is not valid UTF-8 (it would decode to an invalid character), causing JSON parsers to ...
🌐
JSON for Modern C++
json.nlohmann.me › features › binary_values
Binary Values - JSON for Modern C++
0x7B // '{' 0x69 0x06 // i 6 (length of the key) 0x62 0x69 0x6E 0x61 0x72 0x79 // "binary" 0x5B // '[' 0x55 0xCA 0x55 0xFE 0x55 0xBA 0x55 0xBE // content (each byte prefixed with 'U') 0x5D // ']' 0x7D // '}' The following code uses the type and size optimization for BJData: // convert to BJData using the size and type optimization auto v = json::to_bjdata(j, true, true); The resulting vector has 22 elements; the optimization is not effective for examples with few values:
🌐
Python
docs.python.org › 3 › library › json.html
JSON encoder and decoder — Python 3.14.8 documentation
fp (file-like object) – The file-like object obj will be serialized to. The json module always produces str objects, not bytes objects, therefore fp.write() must support str input.
🌐
n8n
community.n8n.io › questions
Read contents of Byte array containing JSON file - Questions - n8n Community
August 18, 2022 - Hi all, Does anyone know how to convert a byte array which contains a JSON file in such a way that the contents can be processed by N8N? The data is coming from the API https://api.crayon.com/api/v1/billingstatements/{…