Android解析JSON并避免如果JSONException导致应用崩溃 [英] Android parse JSON and avoid app crashing if JSONException

查看:795
本文介绍了Android解析JSON并避免如果JSONException导致应用崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序将POST请求发送到服务器,并使用JSON格式获取响应.

my app sends a POST request to a server and gets a response using JSON format.

有时,我的JSON响应为空"(如果请求超时). 在这种情况下,我需要通知用户超时(对话或吐司),并避免应用崩溃.

Sometimes my JSON response is "null" (if the request goes in time out). In that case I need to notify the user about the timeout (dialog or toast) and avoid the app to crash.

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

谢谢! 马可

推荐答案

为避免解析json时应用程序崩溃,请尝试以下方法:

to avoid the crach of your app while parsing your json , try this :

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


}

这篇关于Android解析JSON并避免如果JSONException导致应用崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆