How to Create InputStream Object from JsonObject

30,536

Solution 1

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

Solution 2

if you want bytes, use this

json.toString().getBytes()

or write a File savedFile contains json.toString, and then

InputStream fis = new FileInputStream(savedFile);
Share:
30,536
This 0ne Pr0grammer
Author by

This 0ne Pr0grammer

Updated on July 09, 2022

Comments

  • This 0ne Pr0grammer
    This 0ne Pr0grammer almost 2 years

    I'm trying to figure out how one goes about retrieving the raw bytes stored in a JsonObject and turns that into an InputStream object?

    I figured it might be something like:

    InputStream fis = new FileInputStream((File)json.getJsonObject("data"));
    

    Granted I haven't tried that out, but just wanted to know if anyone had any experience with this and knew the preferred way to do it?

  • This 0ne Pr0grammer
    This 0ne Pr0grammer almost 10 years
    So your solution does work, but I have a question as far as if you pass a file down into your rest call, why does it automatically convert that into an InputStream on the java side?
  • Chthonic Project
    Chthonic Project almost 10 years
    The String is converted to a sequence of bytes, which is, in turn, converted to an InputStream.
  • Ayyappa
    Ayyappa about 3 years
    Note that tostring method of JSONObject is not safe for non-ascii chars. It won't encode in utf-8