[java] Convert InputStream to JSONObject

I am converting InputStream to JSONObject using following code. My question is, is there any simple way to convert InputStream to JSONObject. Without doing InputStream -> BufferedReader -> StringBuilder -> loop -> JSONObject.toString().

    InputStream inputStreamObject = PositionKeeperRequestTest.class.getResourceAsStream(jsonFileName);
    BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStreamObject, "UTF-8"));
    StringBuilder responseStrBuilder = new StringBuilder();

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

    JSONObject jsonObject = new JSONObject(responseStrBuilder.toString());

This question is related to java android json inputstream

The answer is


Since you're already using Google's Json-Simple library, you can parse the json from an InputStream like this:

InputStream inputStream = ... //Read from a file, or a HttpRequest, or whatever.
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject)jsonParser.parse(
      new InputStreamReader(inputStream, "UTF-8"));

If you don't want to mess with ready libraries you can just make a class like this.

public class JsonConverter {

//Your class here, or you can define it in the constructor
Class requestclass = PositionKeeperRequestTest.class;

//Filename
String jsonFileName;

//constructor
public myJson(String jsonFileName){
    this.jsonFileName = jsonFileName;
}


//Returns a json object from an input stream
private JSONObject getJsonObject(){

    //Create input stream
    InputStream inputStreamObject = getRequestclass().getResourceAsStream(jsonFileName);

   try {
       BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStreamObject, "UTF-8"));
       StringBuilder responseStrBuilder = new StringBuilder();

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

       JSONObject jsonObject = new JSONObject(responseStrBuilder.toString());

       //returns the json object
       return jsonObject;

   } catch (IOException e) {
       e.printStackTrace();
   } catch (JSONException e) {
       e.printStackTrace();
   }

    //if something went wrong, return null
    return null;
}

private Class getRequestclass(){
    return requestclass;
}
}

Then, you can use it like this:

JSONObject jObject = new JsonConverter(FILE_NAME).getJsonObject();

This code works

BufferedReader bR = new BufferedReader(  new InputStreamReader(inputStream));
String line = "";

StringBuilder responseStrBuilder = new StringBuilder();
while((line =  bR.readLine()) != null){

    responseStrBuilder.append(line);
}
inputStream.close();

JSONObject result= new JSONObject(responseStrBuilder.toString());       

Another solution: use flexjson.jar: http://mvnrepository.com/artifact/net.sf.flexjson/flexjson/3.2

List<yourEntity> yourEntityList = deserializer.deserialize(new InputStreamReader(input));

Here is a solution that doesn't use a loop and uses the Android API only:

InputStream inputStreamObject = PositionKeeperRequestTest.class.getResourceAsStream(jsonFileName);
byte[] data = new byte[inputStreamObject.available()];
if(inputStreamObject.read(data) == data.length) {
    JSONObject jsonObject = new JSONObject(new String(data));
}

use JsonReader in order to parse the InputStream. See example inside the API: http://developer.android.com/reference/android/util/JsonReader.html


This worked for me:

JSONArray jsonarr = (JSONArray) new JSONParser().parse(new InputStreamReader(Nameofclass.class.getResourceAsStream(pathToJSONFile)));
JSONObject jsonobj = (JSONObject) new JSONParser().parse(new InputStreamReader(Nameofclass.class.getResourceAsStream(pathToJSONFile)));

InputStream inputStreamObject = PositionKeeperRequestTest.class.getResourceAsStream(jsonFileName);
JSONObject jsonObject = new JSONObject(IOUtils.toString(inputStreamObject));

Simple Solution:

JsonElement element = new JsonParser().parse(new InputStreamReader(inputStream));
JSONObject jsonObject = new JSONObject(element.getAsJsonObject().toString());

You can use this api https://code.google.com/p/google-gson/
It's simple and very useful,

Here's how to use the https://code.google.com/p/google-gson/ Api to resolve your problem

public class Test {
  public static void main(String... strings) throws FileNotFoundException  {
    Reader reader = new FileReader(new File("<fullPath>/json.js"));
    JsonElement elem = new JsonParser().parse(reader);
    Gson gson  = new GsonBuilder().create();
   TestObject o = gson.fromJson(elem, TestObject.class);
   System.out.println(o);
  }


}

class TestObject{
  public String fName;
  public String lName;
  public String toString() {
    return fName +" "+lName;
  }
}


json.js file content :

{"fName":"Mohamed",
"lName":"Ali"
}

you could use an Entity:

FileEntity entity = new FileEntity(jsonFile, "application/json");
String jsonString = EntityUtils.toString(entity)

The best solution in my opinion is to encapsulate the InputStream in a JSONTokener object. Something like this:

JSONObject jsonObject = new JSONObject(new JSONTokener(inputStream));

Make use of Jackson JSON Parser

ObjectMapper mapper = new ObjectMapper();
Map<String,Object> map = mapper.readValue(inputStreamObject,Map.class);

If you want specifically a JSONObject then you can convert the map

JSONObject json = new JSONObject(map);

Refer this for the usage of JSONObject constructor http://stleary.github.io/JSON-java/index.html


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to inputstream

Convert InputStream to JSONObject How to read all of Inputstream in Server Socket JAVA Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList? How to create streams from string in Node.Js? How can I read a text file in Android? Can you explain the HttpURLConnection connection process? Open URL in Java to get the content How to convert byte[] to InputStream? Read input stream twice AmazonS3 putObject with InputStream length example