Get the bytes of the string:

obj.toString().getBytes(theCharset);
Answer from MByD on Stack Overflow
🌐
Tabnine
tabnine.com › home page › code › java › java.io.bytearrayoutputstream
java.io.ByteArrayOutputStream.toString java code examples | Tabnine
@Test public void canFormatEmptyObject() { json.assemble( new MappingRepresentation( "empty" ) { @Override protected void serialize( MappingSerializer serializer ) { } } ); assertEquals( JsonHelper.createJsonFrom( Collections.emptyMap() ), stream.toString() ); } Returns the contents of this ByteArrayOutputStream as a string.
Top answer
1 of 1
5

You should use mapper.readValue to deserialize JSON into an object.

Using raw Jackson without the Jackson-Kotlin module:

val map: Map<String, String> = JSON.readValue("""{"name" :"test"}""",
                      object : TypeReference<Map<String, String>>() {})

This passes in an object expression with superclass TypeReference specifying the the type you are wanting to create with full generics still intact (you method suffers from type erasure).

Instead, if you are using the Jackson-Kotlin module you only need:

val map: Map<String, String> = JSON.readValue("""{"name" :"test"}""")

Since it has helper/extension functions to hide some of the uglier things like TypeReference creation.

You should always use the Jackson-Kotlin module with Kotlin code so that you can instantiate any type of Kotlin object including data classes that have all val parameters and no default constructors, have it understand nullability, and also deal with default values for constructor parameters. A simple stand-alone example:

import com.fasterxml.jackson.module.kotlin.*

val JSON = jacksonObjectMapper() // creates ObjectMapper() and adds Kotlin module in one step

val map: Map<String, String> = JSON.readValue("""{"name" :"test"}""")

Notice the import .* so that it picks up all the extension functions otherwise you need to explicitly import: com.fasterxml.jackson.module.kotlin.readValue

Or in your case the modified code would be:

import com.fasterxml.jackson.module.kotlin.readValue

val objectMapper = jacksonObjectMappe() // instead of ObjectMapper()

... 

@POST @Path("/test")
fun test(@Context request: ContainerRequest): Response {
    val bodyAsString = request.entityStream.bufferedReader().readText() 
    val map: Map<String, Any> = when (request.headers.getFirst("Content-Type")) {
        "application/json" -> objectMapper.readValue(bodyAsString) 
        "application/x-www-form-urlencoded" -> LinkedHashMap()
        else -> throw UnsupportedOperationException()
    }
    //....handle the map
    return Response.status(200).build()
}

The code has also been cleaned up a little to remove the use of a var and to read the entity stream in a more Kotlin friendly way.

Also note that the Content-Type header may be more complicated, it could contain encoding as well such as:

Content-type: application/json; charset=utf-8

So you may want a utility function that checks if the header is "equal to application/json or starts with application/json;" instead of only an equality check.

Lastly you could pass the request.entityStream directly to objectMapper.readValue and never copy it into a string at all. There are various overloads for readValue that are helpful for these types of inputs.

🌐
Tutorialspoint
tutorialspoint.com › java › io › bytearrayoutputstream_tostring_string.htm
Java - ByteArrayOutputStream toString(String charsetName) method
The Java ByteArrayOutputStream toString(String charsetName) method converts the stream's contents using the specified charsetName. The malformed-input and unmappable-character sequences are replaced by the default replacement string for the
🌐
GitHub
github.com › FasterXML › jackson-databind › issues › 3493
Can't serialize `ByteArrayOutputStream` value when using jackson 2.13.0 · Issue #3493 · FasterXML/jackson-databind
May 24, 2022 - Reload to refresh your session. ... There was an error while loading. Please reload this page. ... ByteArrayOutputStream bos = new ByteArrayOutputStream() ObjectMapper om = objectMapper(); String json = om.writeValueAsString(bos); public static ObjectMapper objectMapper() { ObjectMapper mapper ...
Published   May 24, 2022
Author   JavaRukawa
🌐
Google
developers.google.com › j2objc › bytearrayoutputstream
ByteArrayOutputStream | J2ObjC | Google for Developers
July 10, 2024 - Converts the buffer's contents into a string by decoding the bytes using the named charset. The length of the new String is a function of the charset, and hence may not be equal to the length of the byte array.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › io › ByteArrayOutputStream.html
ByteArrayOutputStream (Java Platform SE 8 )
March 16, 2026 - Converts the buffer's contents into a string by decoding the bytes using the named charset. The length of the new String is a function of the charset, and hence may not be equal to the length of the byte array.
Find elsewhere
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.io.bytearrayoutputstream.tostring
ByteArrayOutputStream.ToString Method (Java.IO) | Microsoft Learn
Converts the buffer's contents into a string by decoding the bytes using the specified java.nio.charset.Charset charset.
🌐
GeeksforGeeks
geeksforgeeks.org › java › bytearrayoutputstream-tostring-method-in-java-with-examples
ByteArrayOutputStream toString() method in Java with Examples - GeeksforGeeks
July 15, 2025 - GEEKS 2. The toString(String charsetName) method of ByteArrayOutputStream class in Java is used convert the buffer content of the ByteArrayOutputStream into the string using specified charsetName which is passed as string to this method.
🌐
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 - Here, we create a Gson object. Then, we convert thе bytеArray to a string using thе String constructor with еncoding spеcifiеd as UTF-8. Moreover, we utilize the fromJson() method to convеrt thе bytеArray into a JSON string.
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.

🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › io › ByteArrayOutputStream.html
ByteArrayOutputStream (Java Platform SE 7 )
Converts the buffer's contents into a string by decoding the bytes using the specified charsetName. The length of the new String is a function of the charset, and hence may not be equal to the length of the byte array.
🌐
javathinking
javathinking.com › blog › convert-java-io-outputstream-to-string
Converting Java IO OutputStream to String — javathinking.com
You may write data to an OutputStream and then convert it to a string to send it as a JSON or XML payload. Testing: In unit tests, you may want to verify the output written to an OutputStream by converting it to a string and comparing it with ...
🌐
Coderanch
coderanch.com › t › 329194 › java › ByteArrayOutputStream-String
ByteArrayOutputStream to String (Java in General forum at Coderanch)
What is the SQL datatype of the field, and how did you get the data into a ByteArrayOutputStream? I'm guessing it was a BLOB, in which case it's irrelevant that the database uses UTF-8 - you need to know what encoding was used by whoever created the BLOB. ... I think your problem is that java Strings are unicode format and utf8 is not.
🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › java.base › java › io › ByteArrayOutputStream.html
ByteArrayOutputStream (Java SE 11 & JDK 11 )
January 20, 2026 - Converts the buffer's contents into a string by decoding the bytes using the named charset. This method is equivalent to #toString(charset) that takes a charset. ... ByteArrayOutputStream b = ...
🌐
Coderanch
coderanch.com › t › 422694 › java › ByteArray-JSON
ByteArray in JSON (Web Services forum at Coderanch)
December 24, 2008 - syntax error, unexpected TINVALID at line 10 Parsing failed Do you know if there's a standard for placing a byte array in a json message. The way I encode it right now is something like: Thanks in advance! ... Since many byte values turn into illegal characters if you try String conversion, you will have to use base64 encoding to create a String of legal characters.
🌐
Stack Overflow
stackoverflow.com › questions › 72641647 › json-obj-to-string-to-bytes-to-bytearrayinputstream-throws-outofmemory-error
java - Json Obj to String to Bytes to ByteArrayInputStream throws OutOfMemory Error - Stack Overflow
I have a JsonString that needs to be written in file to proceed with further processing. I've written the below code for file writing. val json = "{}" // sample Json. val jsonString = new StringBuilder() val formatjson = PrettyParams.nospace.copy(preserveOrder = true).pretty(json) jsonString.append(formatjson) val tmpFileIS = new ByteArrayInputStream( jsonString.toString().getBytes() ) try { IOUtils.copyLarge(tmpFileIS, tmpBufferedOutputStream) tmpBufferedOutputStream.flush() } catch { case e: Exception => { e.printStackTrace() throw e } } finally { tmpFileIS.close() }