Convert InputStream to JSONObject Convert InputStream to JSONObject android android

Convert InputStream to JSONObject


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 constructorClass requestclass = PositionKeeperRequestTest.class;//FilenameString jsonFileName;//constructorpublic myJson(String jsonFileName){    this.jsonFileName = jsonFileName;}//Returns a json object from an input streamprivate 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();