Convert InputStream to JSONObject

JavaAndroidJsonInputstream

Java Problem Overview


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());

Java Solutions


Solution 1 - Java

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"));

Solution 2 - Java

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

Solution 3 - Java

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();

Solution 4 - Java

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());       

Solution 5 - Java

You can use this api https://code.google.com/p/google-gson/<br> 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"
}

Solution 6 - Java

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

Solution 7 - Java

Simple Solution:

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

Solution 8 - Java

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

Solution 9 - Java

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

Solution 10 - Java

you could use an Entity:

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

Solution 11 - Java

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

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

Solution 12 - Java

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

Solution 13 - Java

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));
}

Solution 14 - Java

You can use this nifty method I made as suggested here:

JSONObject getJsonFromInStream(InputStream inputStream ) throws IOException, JSONException {
    BufferedReader bR = new BufferedReader(  new InputStreamReader(inputStream));
    String line = "";

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

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

    return new JSONObject(responseStrBuilder.toString());
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAAVView Question on Stackoverflow
Solution 1 - JavaSasanka PanguluriView Answer on Stackoverflow
Solution 2 - Javaiftach barshemView Answer on Stackoverflow
Solution 3 - JavaArthurView Answer on Stackoverflow
Solution 4 - JavaTharindu DhanushkaView Answer on Stackoverflow
Solution 5 - JavaelhajView Answer on Stackoverflow
Solution 6 - JavaMuraliView Answer on Stackoverflow
Solution 7 - JavaSurendra KumarView Answer on Stackoverflow
Solution 8 - JavaDaniele ZagnoniView Answer on Stackoverflow
Solution 9 - JavaSandeep AgarwalView Answer on Stackoverflow
Solution 10 - JavaBlackbeltView Answer on Stackoverflow
Solution 11 - Javamig8View Answer on Stackoverflow
Solution 12 - JavaE G NidheepView Answer on Stackoverflow
Solution 13 - JavaBitByteDogView Answer on Stackoverflow
Solution 14 - JavaTrake VitalView Answer on Stackoverflow