You can convert a JSONObject into its String representation, and then convert that String into an InputStream.

The code in the question has a JSONObject being cast into File, but I am not sure if that works as intended. The following, however, is something I have done before (currently reproduced from memory):

String str = json.getJSONObject("data").toString();
InputStream is = new ByteArrayInputStream(str.getBytes());

Note that the toString() method for JSONObject overrides the one in java.lang.Object class.

From the Javadoc:

Returns: a printable, displayable, portable, transmittable representation of the object, beginning with { (left brace) and ending with } (right brace).

Answer from Chthonic Project on Stack Overflow
🌐
GitHub
gist.github.com › KengoTODA › 1159286
InputStream from JSONObject. This class will help feeding JSON from the application server. · GitHub
InputStream from JSONObject. This class will help feeding JSON from the application server. - JSONInputStream.diff
🌐
Baeldung
baeldung.com › home › java › java string › java string to inputstream
Java String to InputStream | Baeldung
January 5, 2024 - Let’s start with a simple example using Java to do the conversion — using an intermediary byte array: @Test public void givenUsingPlainJava_whenConvertingStringToInputStream_thenCorrect() throws IOException { String initialString = "text"; InputStream targetStream = new ByteArrayInputStream(initialString.getBytes()); }
🌐
Oracle
docs.oracle.com › javame › 8.0 › api › json › api › com › oracle › json › stream › JsonParserFactory.html
JsonParserFactory (JSON Documentation)
JsonParser createParser(java.io.InputStream in, java.lang.String charset) throws java.io.UnsupportedEncodingException · Creates a JSON parser from the specified byte stream. The bytes of the stream are decoded to characters using the specified charset.
Top answer
1 of 11
78

I would suggest you have to use a Reader to convert your InputStream in.

BufferedReader streamReader = new BufferedReader(new InputStreamReader(in, "UTF-8")); 
StringBuilder responseStrBuilder = new StringBuilder();

String inputStr;
while ((inputStr = streamReader.readLine()) != null)
    responseStrBuilder.append(inputStr);
new JSONObject(responseStrBuilder.toString());

I tried in.toString() but it returns:

getClass().getName() + '@' + Integer.toHexString(hashCode())

(like documentation says it derives to toString from Object)

2 of 11
39

All the current answers assume that it is okay to pull the entire JSON into memory where the advantage of an InputStream is that you can read the input little by little. If you would like to avoid reading the entire Json file at once then I would suggest using the Jackson library (which is my personal favorite but I'm sure others like Gson have similar functions).

With Jackson you can use a JsonParser to read one section at a time. Below is an example of code I wrote that wraps the reading of an Array of JsonObjects in an Iterator. If you just want to see an example of Jackson, look at the initJsonParser, initFirstElement, and initNextObject methods.

public class JsonObjectIterator implements Iterator<Map<String, Object>>, Closeable {
    private static final Logger LOG = LoggerFactory.getLogger(JsonObjectIterator.class);

    private final InputStream inputStream;
    private JsonParser jsonParser;
    private boolean isInitialized;

    private Map<String, Object> nextObject;

    public JsonObjectIterator(final InputStream inputStream) {
        this.inputStream = inputStream;
        this.isInitialized = false;
        this.nextObject = null;
    }

    private void init() {
        this.initJsonParser();
        this.initFirstElement();
        this.isInitialized = true;
    }

    private void initJsonParser() {
        final ObjectMapper objectMapper = new ObjectMapper();
        final JsonFactory jsonFactory = objectMapper.getFactory();

        try {
            this.jsonParser = jsonFactory.createParser(inputStream);
        } catch (final IOException e) {
            LOG.error("There was a problem setting up the JsonParser: " + e.getMessage(), e);
            throw new RuntimeException("There was a problem setting up the JsonParser: " + e.getMessage(), e);
        }
    }

    private void initFirstElement() {
        try {
            // Check that the first element is the start of an array
            final JsonToken arrayStartToken = this.jsonParser.nextToken();
            if (arrayStartToken != JsonToken.START_ARRAY) {
                throw new IllegalStateException("The first element of the Json structure was expected to be a start array token, but it was: " + arrayStartToken);
            }

            // Initialize the first object
            this.initNextObject();
        } catch (final Exception e) {
            LOG.error("There was a problem initializing the first element of the Json Structure: " + e.getMessage(), e);
            throw new RuntimeException("There was a problem initializing the first element of the Json Structure: " + e.getMessage(), e);
        }

    }

    private void initNextObject() {
        try {
            final JsonToken nextToken = this.jsonParser.nextToken();

            // Check for the end of the array which will mean we're done
            if (nextToken == JsonToken.END_ARRAY) {
                this.nextObject = null;
                return;
            }

            // Make sure the next token is the start of an object
            if (nextToken != JsonToken.START_OBJECT) {
                throw new IllegalStateException("The next token of Json structure was expected to be a start object token, but it was: " + nextToken);
            }

            // Get the next product and make sure it's not null
            this.nextObject = this.jsonParser.readValueAs(new TypeReference<Map<String, Object>>() { });
            if (this.nextObject == null) {
                throw new IllegalStateException("The next parsed object of the Json structure was null");
            }
        } catch (final Exception e) {
            LOG.error("There was a problem initializing the next Object: " + e.getMessage(), e);
            throw new RuntimeException("There was a problem initializing the next Object: " + e.getMessage(), e);
        }
    }

    @Override
    public boolean hasNext() {
        if (!this.isInitialized) {
            this.init();
        }

        return this.nextObject != null;
    }

    @Override
    public Map<String, Object> next() {
        // This method will return the current object and initialize the next object so hasNext will always have knowledge of the current state

        // Makes sure we're initialized first
        if (!this.isInitialized) {
            this.init();
        }

        // Store the current next object for return
        final Map<String, Object> currentNextObject = this.nextObject;

        // Initialize the next object
        this.initNextObject();

        return currentNextObject;
    }

    @Override
    public void close() throws IOException {
        IOUtils.closeQuietly(this.jsonParser);
        IOUtils.closeQuietly(this.inputStream);
    }

}

If you don't care about memory usage, then it would certainly be easier to read the entire file and parse it as one big Json as mentioned in other answers.

🌐
Yenrab
yenrab.github.io › qcJSON › documentation › org › quickconnectfamily › json › JSONInputStream.html
JSONInputStream
The JSONInputStream class is used when you want to read JSON from any type of InputStream such as a FileInputStream or a SocketInputStream. If you want to convert JSON string to the appropriate Object and Array representations use the JSONUtilities.parse methods instead.
🌐
CodingTechRoom
codingtechroom.com › question › how-to-create-an-inputstream-object-from-a-jsonobject-in-java
How to create an InputStream object from a JSONObject in Java? - CodingTechRoom
Sending JSON data to APIs that accept InputStream. Convert the JSONObject to a String and then to an InputStream using ByteArrayInputStream.
🌐
GitHub
gist.github.com › RealDeanZhao › af5ef2d1d6eb98729103cc16028e177f
Parse InputStream to JsonObject · GitHub
JsonObject json; try { JsonElement element = new JsonParser().parse( new InputStreamReader(responseEntity.getBody().getInputStream()) ); json = element.getAsJsonObject(); } catch (IOException e) { throw new RuntimeException(e.getLocalizedMessage()); ...
Find elsewhere
🌐
Radomir Sohlich
sohlich.github.io › post › jackson
Streaming JSON with Jackson - Radomir Sohlich
February 8, 2017 - The parsing of stream is possible via JsonParser object, which uses token approach. InputStream is = new FileInputStream("data.json"); JsonFactory factory = new JsonFactory(); JsonParser parser = factory.createJsonParser(is);
🌐
Mkyong
mkyong.com › home › java › how to convert string to inputstream in java
How to convert String to InputStream in Java - Mkyong.com
February 13, 2022 - In Java, we can use ByteArrayInputStream to convert a String to an InputStream.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-convert-string-to-inputstream
Java Program to Convert String to InputStream - GeeksforGeeks
June 12, 2021 - We can convert a String to an InputStream object by using the ByteArrayInputStream class. The ByteArrayInputStream is a subclass present in InputStream class.
🌐
Developers Corner
avaldes.com › converting-json-to-and-from-java-object-using-jackson
Converting JSON to and From Java Object using Jackson
March 18, 2016 - In this next example, we show you how Jackson can perform the deserialization from JSON to Java objects using a Reader, which is the abstract class for all of the Readers in the Java IO API. Subclasses include BufferedReader, CharArrayReader, FilterReader, InputStreamReader, PipedReader, and StringReader.
🌐
TutorialsPoint
tutorialspoint.com › how-to-convert-a-string-to-an-inputstream-object-in-java
How to convert a String to an InputStream object in Java?
August 1, 2020 - In this article, we will learn how we can use the ByteArrayInputStream class to convert a string into an InputStream with the help of example programs. Before discussing that, we need to learn about the InputStream and BufferedReader classes and the getBytes() method first:
🌐
Medium
medium.com › javarevisited › how-to-convert-string-to-inputstream-in-java-3812623cb3ee
How to Convert String to InputStream in Java | by Suraj Mishra | Javarevisited | Medium
July 17, 2023 - So for that to work, we need to convert String to InputStream. I had a list of in-memory values as a List of Entities. The first thing I had to do is to convert the List of Entity to List of Strings and then add new line char at the end of the line. ... A humble place to learn Java and Programming better.
🌐
W3Docs
w3docs.com › java
How do I convert a String to an InputStream in Java?
String str = "Hello, world!"; InputStream is = new ByteArrayInputStream(str.getBytes("UTF-8")); ... In this case, the getBytes method is called with the "UTF-8" character encoding, so the resulting byte array will contain the UTF-8 encoded version ...
🌐
Baeldung
baeldung.com › home › json › converting a bufferedreader to a jsonobject
Converting a BufferedReader to a JSONObject | Baeldung
May 5, 2025 - @Test public void givenValidJson_whenUsingBufferedReader_thenJSONTokenerConverts() { byte[] b = "{ \"name\" : \"John\", \"age\" : 18 }".getBytes(StandardCharsets.UTF_8); InputStream is = new ByteArrayInputStream(b); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is)); JSONTokener tokener = new JSONTokener(bufferedReader); JSONObject json = new JSONObject(tokener); assertNotNull(json); assertEquals("John", json.get("name")); assertEquals(18, json.get("age")); } Now, let’s look at another approach to obtain the JSONObject by first converting a BufferedReader to a String.
🌐
Delft Stack
delftstack.com › home › howto › java › java string to inputstream
How to Convert String to InputStream in Java | Delft Stack
February 2, 2024 - First, we use getBytes() to get the bytes from exampleString with the charset UTF_8, and then pass it to ByteArrayInputStream. To check if we succeed in our goal, we can read the inputStream using read(), and convert every byte to a char.
🌐
Codementor
codementor.io › community › how to parse json assets with gson
How to parse json assets with gson | Codementor
March 30, 2017 - String json = null; try { InputStream inputStream = getAssets().open("events.json"); int size = inputStream.available(); byte[] buffer = new byte[size]; inputStream.read(buffer); inputStream.close(); json = new String(buffer, "UTF-8"); } catch ...