How to parse a JSON Input stream

前端 未结 11 1931
野的像风
野的像风 2020-11-30 01:06

I am using java to call a url that returns a JSON object:

url = new URL(\"my URl\");
urlInputStream = url.openConnection().getInputStream();
<
11条回答
  •  感动是毒
    2020-11-30 01:32

    For those that pointed out the fact that you can't use the toString method of InputStream like this see https://stackoverflow.com/a/5445161/1304830 :

    My correct answer would be then :

    import org.json.JSONObject;
    
    public static String convertStreamToString(java.io.InputStream is) {
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }
    
    ...
    
    JSONObject json = new JSONObject(convertStreamToString(url.openStream());
    

提交回复
热议问题