Convert InputStream to JSONObject

前端 未结 13 1868
刺人心
刺人心 2020-12-05 03:52

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 -> Bu

13条回答
  •  旧巷少年郎
    2020-12-05 04:50

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

提交回复
热议问题