【问题标题】:Android parse JSON and avoid app crashing if JSONException如果 JSONException,Android 会解析 JSON 并避免应用程序崩溃
【发布时间】:2011-10-05 18:18:25
【问题描述】:

我的应用程序向服务器发送 POST 请求并使用 JSON 格式获得响应。

有时我的 JSON 响应是“null”(如果请求超时)。 在这种情况下,我需要通知用户超时(对话框或 toast)并避免应用崩溃。

如何正确处理 JSONException 并避免应用崩溃?

谢谢! 马可

【问题讨论】:

  • 除非我遗漏了什么你问你如何捕捉异常并显示一个对话框?
  • try-catch 块是否不够用?

标签: android json exception


【解决方案1】:

为避免在解析 json 时出现应用崩溃,请尝试以下操作:

if (jsonResponse == null) {
       // notify user
} else {
      try {
         // parse json here.
      } catch (JSONException e) {
        Toast.makeText(this,"Error on the response", 3000).show();
      }


}

【讨论】:

    【解决方案2】:

    检查您的 json 响应是否为空。然后才解析 json。

    if (jsonResponse == null) {
           // notify user
    } else {
          // parse json here.
    }
    

    【讨论】:

      【解决方案3】:

      获取完整的异常:

      StatusLine statusLine = response.getStatusLine();
          if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
              ByteArrayOutputStream out = new ByteArrayOutputStream();
              response.getEntity().writeTo(out);
              out.close();
              jsonString = out.toString();
          }
      
          }catch(ConnectException e){             
          // handle your exception here, maybe something like
              Toast.makeText(context,"Error!",5000).show();
              finish(); 
      
          } catch (URISyntaxException e1) {
              e1.printStackTrace();
          } catch (ClientProtocolException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          } catch (Exception e) {
              e.printStackTrace();
          }
      

      【讨论】:

        猜你喜欢
        • 2013-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-22
        相关资源
        最近更新 更多