8

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
  • 2,632
  • 14
  • 57
  • 81
  • 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](http://stackoverflow.com/a/7099314/1377895) – Roman Vottner Feb 19 '16 at 14:56

2 Answers2

24

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

Chthonic Project
  • 8,216
  • 1
  • 43
  • 92
  • 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? – This 0ne Pr0grammer May 30 '14 at 18:14
  • 1
    The `String` is converted to a sequence of bytes, which is, in turn, converted to an `InputStream`. – Chthonic Project May 30 '14 at 21:56
  • Note that tostring method of JSONObject is not safe for non-ascii chars. It won't encode in utf-8 – Ayyappa Apr 01 '21 at 06:37
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);
Yazan
  • 6,074
  • 1
  • 19
  • 33