Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create InputStream Object from JsonObject

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?

like image 307
This 0ne Pr0grammer Avatar asked May 22 '14 20:05

This 0ne Pr0grammer


2 Answers

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

like image 179
Chthonic Project Avatar answered Oct 22 '22 14:10

Chthonic Project


if you want bytes, use this

json.toString().getBytes()

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

InputStream fis = new FileInputStream(savedFile);
like image 27
Yazan Avatar answered Oct 22 '22 14:10

Yazan