Get the bytes of the string:

obj.toString().getBytes(theCharset);
Answer from MByD on Stack Overflow
🌐
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 - ByteArrayOutputStream bos = new ByteArrayOutputStream() ObjectMapper om = objectMapper(); String json = om.writeValueAsString(bos); public static ObjectMapper objectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.setVisibilit...
Published   May 24, 2022
Author   JavaRukawa
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.

🌐
Baeldung
baeldung.com › home › json › jackson › jackson streaming api
Jackson Streaming API | Baeldung
March 26, 2025 - Firstly, we need to create the instance of that object: ByteArrayOutputStream stream = new ByteArrayOutputStream(); JsonFactory jfactory = new JsonFactory(); JsonGenerator jGenerator = jfactory .createGenerator(stream, JsonEncoding.UTF8); Next, ...
🌐
Wordpress
myadventuresincoding.wordpress.com › 2020 › 07 › 11 › java-using-jackson-jsongenerator-to-write-json-to-an-outputstream
Java – Using Jackson JsonGenerator to write JSON to an OutputStream | My Adventures in Coding
August 8, 2021 - import com.fasterxml.jackson.core.JsonEncoding; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import java.io.ByteArrayOutputStream; public class JsonGeneratorExample { public static void main(String[] args) throws Exception { // Create the OutputStream we will be writing JSON to ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // Create a background thread to print out the contents of the OutputStream PrintOutputStreamRunnable runnable = new PrintOutputStreamRunnable(outputStream); Thread thread = new Thread(runnable); thread.s
🌐
Jenkov
jenkov.com › tutorials › java-io › bytearrayoutputstream.html
Java ByteArrayOutputStream
This tutorial explains how to use the ByteArrayOutputStream in Java IO to write data to an OutputStream and capture that data in a byte array.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 54109268 › getting-json-string-with-streaming-gson-with-bytearrayoutputstream-gets-outofmem
android - Getting JSON String with streaming GSON with ByteArrayOutputStream gets OutOfMemoryError - Stack Overflow
January 9, 2019 - @Nullable private static String streamBlaModelsIntoJsonString(List<BlaModel> blaModels) { try { Gson gson = new Gson(); ByteArrayOutputStream out = new ByteArrayOutputStream(); JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8")); writer.setIndent(" "); writer.beginArray(); for (BlaModel blaModel : blaModels) { gson.toJson(blaModel, BlaModel.class, writer); } writer.endArray(); writer.close(); return out.toString("UTF-8"); } catch (IOException e) { e.printStackTrace(); } return null; }
🌐
GitHub
github.com › FasterXML › jackson-databind › issues › 3522
Support serializing `ByteArrayOutputStream` as "simple" Binary value · Issue #3522 · FasterXML/jackson-databind
June 20, 2022 - As a result, ByteArrayOutputStream values are no longer serializable. But it might make sense to make it serializable again. However, the representation as POJO does not make sense: if serialization is to be used, it should: Use public ByteArrayOutStream.toByteArray() to access content · Serialize contents as a Binary value: for JSON backend this means Base64-encoded String; for other backends whatever their representation of Binary values is ·
🌐
Programiz
programiz.com › java-programming › bytearrayoutputstream
Java ByteArrayOutputStream (With Examples)
The ByteArrayOutputStream class of the java.io package can be used to write an array of output data (in bytes).
🌐
Apache Commons
commons.apache.org › proper › commons-io › javadocs › api-2.5 › org › apache › commons › io › output › ByteArrayOutputStream.html
ByteArrayOutputStream (Apache Commons IO 2.5 API)
This is an alternative implementation of the ByteArrayOutputStream class. The original implementation only allocates 32 bytes at the beginning. As this class is designed for heavy duty it starts at 1024 bytes. In contrast to the original it doesn't reallocate the whole memory block but allocates ...
🌐
Javatpoint
javatpoint.com › java-bytearrayoutputstream-class
Java ByteArrayOutputStream Class - javatpoint
Java ByteArrayOutputStream Class for beginners and professionals with examples on Java IO or Input Output in Java with input stream, output stream, reader and writer class. The java.io package provides api to reading and writing data.
🌐
GeeksforGeeks
geeksforgeeks.org › java › io-bytearrayoutputstream-class-java
Java.io.ByteArrayOutputStream() Class in Java - GeeksforGeeks
July 23, 2025 - public String toString(String charsetName) Parameters : -------------- Return : the content of Output Stream by converting it to platform's default Character set Java Program illustrating the use ByteArrayOutputStream class methods :
🌐
Java Guides
javaguides.net › 2018 › 08 › bytearrayoutputstream-class-in-java.html
ByteArrayOutputStream Class in Java
June 21, 2024 - ByteArrayOutputStream is an implementation of an output stream that uses a byte array as the destination.
🌐
Baeldung
baeldung.com › home › java › java io › guide to java outputstream
Guide to Java OutputStream | Baeldung
December 3, 2025 - ByteArrayOutputStream is an implementation of OutputStream that can write data into a byte array.
🌐
Medium
medium.com › @lavishj77 › java-i-o-byte-stream-implementation-6acf5a9ec848
Java I/O Byte Stream Implementation | by Lavish Jain | Medium
April 16, 2022 - So for this we can use Apache common's IOUtils.toByteArray(fileInputStream) to read data from fileInputStream into bytearray. Internally this creates a ByteArrayOutputStream and copies the bytes from FileInputStream to the ByteArrayOutputStream, then calls toByteArray().