55

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());
AAV
  • 3,785
  • 8
  • 32
  • 59
  • What you have is fine. You could extract the `BufferedReader` reading to a static helper method and re-use that. Some 3rd party libraries already do that. – Sotirios Delimanolis Mar 17 '14 at 17:52

14 Answers14

39

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"));
Sasanka Panguluri
  • 3,058
  • 4
  • 32
  • 54
  • 4
    dunno why, but this code throws an exception: Exception in thread "main" java.lang.ClassCastException: class org.json.simple.JSONArray cannot be cast to class org.json.JSONObject (org.json.simple.JSONArray and org.json.JSONObject are in unnamed module of loader 'app') – Vinci Feb 25 '19 at 15:03
  • Should this be `JsonParser` instead of `JSONParser`? – klutt Feb 21 '22 at 07:12
17

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

iftach barshem
  • 497
  • 5
  • 17
  • 4
    This should be the accepted answer... the code in the link is simply: JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); – JoelFan May 06 '16 at 02:27
  • 8
    It's (almost) a link-only answer. You'd be much better off by including the gist in your answer. – Aleks G Nov 07 '16 at 14:24
10

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();
Arthur
  • 3,636
  • 5
  • 19
  • 25
10

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());       
Tunaki
  • 132,869
  • 46
  • 340
  • 423
2

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"
}
elhaj
  • 438
  • 5
  • 10
  • 1
    This doesn't answer the question. Please specify how Gson fixes their issue. – Sotirios Delimanolis Mar 17 '14 at 18:05
  • Also, if the library the questioner is already using offers a solution, try to utilize that library with that solution. If it doesn't, then express that don't make an answer that basically says "use another library" and then post links to the library. Answers need to explain the links they have associated, not just be link dumps. – zero298 Mar 17 '14 at 18:21
2

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));
  • what do you mean? For using JSONTokener you must add java-json dependency (the same for JSONObject, which is the main topic of this question...) – Daniele Zagnoni Dec 28 '18 at 17:19
  • 8
    The constructor of `JSONTokener` that comes with the Android framework does not take an `InputStream`. Only `String`. – friederbluemle Oct 07 '19 at 02:03
1

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)));
Murali
  • 430
  • 5
  • 10
  • 1
    Please provide some context to your answer, specifically what it is doing, and why it solves the problem. – haxxxton Feb 15 '17 at 07:33
1

Simple Solution:

JsonElement element = new JsonParser().parse(new InputStreamReader(inputStream));
JSONObject jsonObject = new JSONObject(element.getAsJsonObject().toString());
Surendra Kumar
  • 2,787
  • 1
  • 12
  • 10
1

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));
}
BitByteDog
  • 3,074
  • 2
  • 26
  • 39
  • to get string: `BufferedReader in = new BufferedReader(new InputStreamReader( con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); String targetLcl=response.toString();` – CodeToLife Apr 01 '20 at 13:36
1

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

0

you could use an Entity:

FileEntity entity = new FileEntity(jsonFile, "application/json");
String jsonString = EntityUtils.toString(entity)
Blackbelt
  • 156,034
  • 29
  • 297
  • 305
  • 1
    Does `FileEntity` expect a `File` or a `URL` or a `InputStream`? They seem to be getting the `InputStream` from the classpath. – Sotirios Delimanolis Mar 17 '14 at 17:57
  • a File, and the content type. What you mean with "They seem to be getting the InputStream from the classpath"? @SotiriosDelimanolis – Blackbelt Mar 17 '14 at 17:58
  • 3
    They are using `Class#getResourceAsStream()` which returns an `InputStream` for a resource on the classpath. They don't have a `File` here. – Sotirios Delimanolis Mar 17 '14 at 18:01
0

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

List<yourEntity> yourEntityList = deserializer.deserialize(new InputStreamReader(input));
mig8
  • 122
  • 4
0
InputStream inputStreamObject = PositionKeeperRequestTest.class.getResourceAsStream(jsonFileName);
JSONObject jsonObject = new JSONObject(IOUtils.toString(inputStreamObject));
bharatk
  • 4,202
  • 5
  • 16
  • 30
0

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());
}
Trake Vital
  • 1,019
  • 10
  • 18