nesalexy
nesalexy

Reputation: 878

Download JSON from URL(java)

Good evening, I'm sorry for my english. I want to try to deduce, using a link from json in the console. Sometimes is used json-simple-1.1.1.jar. I do not understand what the problem is, writes

Exception in thread "main" java.lang.NullPointerException at kkkkkkkkkkkk.main.main (main.java:34)

    private static final String filePath = "http://ksupulse.tk/get_all.php";

    public static void main(String[] args) throws org.json.simple.parser.ParseException {

        try {
            URL serverAddress = new URL(filePath);
            HttpURLConnection connection = (HttpURLConnection) serverAddress.openConnection(); 
            connection.connect();

            int rc = connection.getResponseCode();
            if(rc == 200) {
                String line = null;
                BufferedReader reader = new BufferedReader(new java.io.InputStreamReader(connection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                while((line = reader.readLine()) != null)
                    sb.append(line + '\n');
                JSONObject obj = (JSONObject) JSONValue.parse(sb.toString());
//error                 
JSONArray array = (JSONArray) obj.get("response"); //<-------err this line 

                for(int i = 0; i < array.size(); i++) {
                    JSONObject list = (JSONObject) ((JSONObject)array.get(i)).get("list");
                    System.out.println(list.get("id")+": "+list.get("name"));
                }
            } else {
                System.out.println("Connect error");
            }
            connection.disconnect();
         } catch (java.net.MalformedURLException e) { 
              e.printStackTrace(); 
            } catch (java.net.ProtocolException e) { 
              e.printStackTrace(); 
            } catch (java.io.IOException e) { 
              e.printStackTrace(); 
            } 



    }

Upvotes: 0

Views: 604

Answers (1)

Dibsyhex
Dibsyhex

Reputation: 117

Can u provide the json text ?This is happening due to improper parsing of json text. The error is "Null Pointer Exception" . These types of error occur when you try to access some undefined resource . A good way to debug this one is to use a general exception and try to find the exact error . Your code is only handling 3 errors .You need to handle other errors also. Try using this.

try{
//Some code
}(Exception e){
System.out.println("Error:"+e.toString());
}

Upvotes: 1

Related Questions