Android应用在解析JSON时崩溃

时间:2017-03-20 14:26:34

标签: android json crash

我正在将String解析为JSON,就像这样

try {
 x = new JSONObject(y);
} catch (Exception e) {
}

它对我来说很好,但我在布料上遇到了非常罕见的崩溃,

Fatal Exception: java.lang.RuntimeException: Unable to start activity ComponentInfo{a.b.c/a.b.XActivity}: java.lang.NullPointerException
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
   at android.app.ActivityThread.access$600(ActivityThread.java:141)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
   at android.os.Handler.dispatchMessage(Handler.java:99)
   at android.os.Looper.loop(Looper.java:137)
   at android.app.ActivityThread.main(ActivityThread.java:5103)
   at java.lang.reflect.Method.invokeNative(Method.java)
   at java.lang.reflect.Method.invoke(Method.java:525)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
   at dalvik.system.NativeStart.main(NativeStart.java)
   Caused by java.lang.NullPointerException
   at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
   at org.json.JSONTokener.nextValue(JSONTokener.java:94)
   at org.json.JSONObject.(JSONObject.java)
   at org.json.JSONObject.(JSONObject.java)
   at com.razorpay.XActivity.onCreate(Unknown Source:1454)
   at android.app.Activity.performCreate(Activity.java:5133)
   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
   at android.app.ActivityThread.access$600(ActivityThread.java:141)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
   at android.os.Handler.dispatchMessage(Handler.java:99)
   at android.os.Looper.loop(Looper.java:137)
   at android.app.ActivityThread.main(ActivityThread.java:5103)
   at java.lang.reflect.Method.invokeNative(Method.java)
   at java.lang.reflect.Method.invoke(Method.java:525)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
   at dalvik.system.NativeStart.main(NativeStart.java)

此崩溃并不是非常罕见,我无法重现它,但我无法理解,当代码已经在内部时,怎么会发生这种情况 试试看。

1 个答案:

答案 0 :(得分:2)

唯一可能为null并导致NullPointerException(假设它实际上来自此代码)的是y变量。此外,捕获所有可能的Throwable对象也不会受到伤害。

所以这可能会有所帮助:

try {
    if (y != null) {
         x = new JSONObject(y);
    }
} catch (Throwable t) {
}