Convert InputStream to JSONObject

前端 未结 13 1855
刺人心
刺人心 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:32

    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());       
    
    0 讨论(0)
  • 2020-12-05 04:33

    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));
    }
    
    0 讨论(0)
  • 2020-12-05 04:36

    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));
    
    0 讨论(0)
  • 2020-12-05 04:38

    Simple Solution:

    JsonElement element = new JsonParser().parse(new InputStreamReader(inputStream));
    JSONObject jsonObject = new JSONObject(element.getAsJsonObject().toString());
    
    0 讨论(0)
  • 2020-12-05 04:42

    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 讨论(0)
  • 2020-12-05 04:44

    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)));
    
    0 讨论(0)
提交回复
热议问题