9

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?

1
  • Just in case if you ever run into a situation where you have to stream the content of a very large JSON object, which might produce OutOfMemory errors on toString() method invocations use mutliple ByteArrayInputStreams as prestented in this post here Commented Feb 19, 2016 at 14:56

2 Answers 2

25

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

Sign up to request clarification or add additional context in comments.

3 Comments

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?
The String is converted to a sequence of bytes, which is, in turn, converted to an InputStream.
Note that tostring method of JSONObject is not safe for non-ascii chars. It won't encode in utf-8
7

if you want bytes, use this

json.toString().getBytes()

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

InputStream fis = new FileInputStream(savedFile);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.