而不是编写自己的功能使用try-catch的inbuild构造。你的问题是,jsonarray或jsonarray.getJSONObject(i)或值本身是一个null,你调用一个null引用的方法。尝试以下操作:
int block_id = 0; //this set's the block_id to 0 as a default.
try {
block_id = Integer.parseInt(jsonarray.getJSONObject(i).getString("block_id")); //this will set block_id to the String value, but if it's not convertable, will leave it 0.
} catch (Exception e) {};
在Java异常用于标记意外情况。例如,将非数字字符串解析为数字(NumberFormatException)或调用空引用(NullPointerException)上的方法。你可以用很多方法来捕捉它们。
try{
//some code
} catch (NumberFormatException e1) {
e.printStackTrace() //very important - handles the Exception but prints the information!
} catch (NullPointerException e2) {
e.printStackTrace();
}
或使用这个事实,他们都扩展异常:
try {
//somecode
} catch (Exception e) {
e.printStackTrace;
};
或从Java 7开始:
try {
//somecode
} catch (NullPointerException | NumberFormatException e) {
e.printStackTrace;
};
注意
我相信,请仔细阅读答案,请记住,在StackOverflow中,我们需要Minimal, Complete, and Verifiable example,其中包括您的异常的StackTrace。在你的情况下,它可能从以下开始:
Exception in thread "main" java.lang.NullPointerException
那么调试就会容易得多。没有它,它只是猜测。
编辑:根据接受的答案
接受的答案是好的,并且将工作很长时间,因为使用key:block_id存储的值将是数字。如果它不是数字,您的应用程序将崩溃。
代替:
JSONObject jObj = jsonarray.getJSONObject(i);
int block_id = jObj.has("block_id") ? jObj.getInt("block_id") : 0;
应该使用:
int block_id;
try{
JSONObject jObj = jsonarray.getJSONObject(i);
block_id = jObj.has("block_id") ? jObj.getInt("block_id") : 0;
} catch (JSONException | NullPointerException e) {
e.printStackTrace();
}