Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()); 
like image 559
AAV Avatar asked Mar 17 '14 17:03

AAV


2 Answers

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")); 
like image 56
Sasanka Panguluri Avatar answered Oct 16 '22 22:10

Sasanka Panguluri


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

like image 45
iftach barshem Avatar answered Oct 16 '22 21:10

iftach barshem