Search code examples
javaandroidjsonjson-simple

Aplication with json-simple crash after non json data


Ive got

 HttpURLConnection urlConnection = null;
        String result = "";
        try {

            String host = "http://www.example.com/json.json";

            URL url = new URL(host);
            urlConnection = (HttpURLConnection) url.openConnection();

            int code = urlConnection.getResponseCode();

            if(code==200){
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                if (in != null) {
                    JSONParser jsonParser = new JSONParser();
                    JSONObject jsonObject = (JSONObject)jsonParser.parse(new InputStreamReader(in, "UTF-8"));
                    result=(String) jsonObject.get("name");
                    System.out.print(jsonObject);
                }
                in.close();
            } else { result="9";}

            return result;
        } catch (MalformedURLException e) {
            result="9";
        } catch (IOException e) {
            result="9";
        }
        catch (ParseException e) {
            e.printStackTrace();
            result="9";
        }

        finally {
            urlConnection.disconnect();
        }
        return result;

When i input valid json data, all is OK, but if i got non json data, i got aplication crash with :

Caused by: java.lang.ClassCastException: java.lang.Long cannot be cast to org.json.simple.JSONObject

I think that

 catch (ParseException e) {
                e.printStackTrace();
                result="9";
            }

should handle this, but no.

So what i must do to avoid situation that aplication will crash when i do not get valid json?


Solution

  • The thrown exception is a ClassCastException. Maybe you can catch that exception also by adding another catch?

    catch (ClassCastException e) {
        e.printStackTrace();
        result="9";
    }