English 中文(简体)
Anders parse JSON公司,如果JSONException的话,避免 app撞
原标题:Android parse JSON and avoid app crashing if JSONException

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

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.

How do I handle correctly the JSONException and avoid the app crash?

Thank you! Marco

最佳回答

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();
      }


}
问题回答

如果你的 j子反应无效,就会进行检查。 当时只有 j子。

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

完全例外:

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();
    }




相关问题
handling exceptions IN Action Filters

Is there a better way to handle exceptions that occur inside an Action Filter itself in ASP .NET MVC? There re 2 ways I can think of at the moment. Using a try catch and setting the HTTP Status ...

既可捕获,又可举出例外。

我有一种办法,可以进入亚洲开发银行,因此,我国的亚行在多瑙河航道中的所有 st子都位于一个试捕区。 它正在追捕Kexception

Cross compiler exception handling - Can it be done safely?

I am doing some maintenance on a C++ windows dll library that is required to work with different VC++ compilers (as I don’t want to address different mangling schemes). I have already eliminated any ...

File Handling Issue

I am developing a tool in c#, at one instance I start writing into a xml file continuously using my tool,when i suddenly restart my machine the particular xml file gets corrupted, what is the reason ...

Watch a memory location/install data breakpoint from code?

We have a memory overwrite problem. At some point, during the course of our program, a memory location is being overwritten and causing our program to crash. the problem happens only in release mode. ...

Unit Test for Exceptions Message

Is there a simple (Attribute-driven) way to have the following test fail on the message of the exception. [TestMethod()] [ExpectedException(typeof(ArgumentException))] public void ExceptionTestTest() ...

热门标签