非json数据后使用json-simple崩溃的应用

时间:2018-07-07 09:13:52

标签: java android json json-simple

我有

 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;

当我输入有效的json数据时,一切正常,但是,如果我得到的不是json数据,则发生复制崩溃:

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

我认为

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

应该处理这个,但不能。

那我该怎么做才能避免当我没有得到有效的json时应用崩溃的情况?

3 个答案:

答案 0 :(得分:0)

抛出的异常是ClassCastException。也许您还可以通过添加另一个catch来捕获该异常?

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

答案 1 :(得分:0)

尝试执行此操作以发出http请求

class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            URL myUrl = null;
            HttpURLConnection conn = null;
            String response = "";
            //String data = params[0];

            try {
                myUrl = new URL("http://www.example.com/json.json");
                conn = (HttpURLConnection) myUrl.openConnection();
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);

                //one long string, first encode is the key to get the  data on your web
                //page, second encode is the value, keep concatenating key and value.
                //theres another ways which easier then this long string in case you are
                //posting a lot of info, look it up.
                String postData = URLEncoder.encode("key", "UTF-8") + "=" +
                        URLEncoder.encode("value", "UTF-8");
                OutputStream os = conn.getOutputStream();

                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                bufferedWriter.write(postData);
                bufferedWriter.flush();
                bufferedWriter.close();

                InputStream inputStream = conn.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    response += line;
                }
                bufferedReader.close();
                inputStream.close();
                conn.disconnect();
                os.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return response;
        }

        @Override
        protected void onPostExecute(String s) {
            try {
                JSONObject jsonObject = new JSONObject(s);
            } catch (JSONException e) {
                //s may not be json
            }
        }
    }

答案 2 :(得分:0)

从Json对象获取String之前,请检查Json对象是否不为null且具有该字符串。然后尝试获取它。

if (jsonObject!=null && jsonObject.has("name"))
 {
     result = jsonObject.get("name");
     System.out.print(result);
  }