未处理的异常 org.json.jsonexception

unhandled exception org.json.jsonexception

我正在开发一个 android 应用程序,该应用程序必须将 java 对象以 json 格式保存到 SQLite 数据库中。我为这个操作编写了代码,然后他们必须提取 Json 对象并将其重新转换为 Java 对象。 当我尝试调用将 json 对象反序列化为字符串的方法时,我在 Android Studio 中发现了这个错误:unhandled exception org.json.jsonexception

当我尝试捕获 JSONException e 时,程序运行但不反序列化 json 对象。

这是方法的代码:

private void read() throws JSONException {
    SQLiteDatabase db = mMioDbHelper.getWritableDatabase();
    String[] columns = {"StringaAll"};
    Cursor c = db.query("Alle", columns, null, null, null, null,null );
    while(c.moveToNext()) {
        String stringaRis =  c.getString(0);
        JSONObject jObj = new JSONObject(stringaRis);
        String sPassoMed = jObj.getString("passoMed");
        final TextView tView = (TextView) this.findViewById(R.id.mainProvaQuery);
        tView.setText(sPassoMed);
        // }
    }
}

你能帮帮我吗?

是的,你需要捕获异常。

但是当你抓住它的时候,你不应该把它扔在地上。您的应用程序需要对异常做一些事情。或者,如果您/它不希望在运行时发生异常,那么至少您应该报告它。这是一个最小示例(针对 Android 应用)

try {
    ...
    JSONObject jObj = new JSONObject(stringaRis);
    ...
} catch (JSONException e) {
    Log.e("MYAPP", "unexpected JSON exception", e);
    // Do something to recover ... or kill the app.
}

当然,这并不能解决你的问题。您需要做的下一件事是弄清楚为什么会出现异常。首先阅读您已记录到 logcat.

的异常消息

关于此异常消息:

org.json.JSONException: Value A of type java.lang.String cannot be converted to JSONObject

我假设它是由这一行抛出的:

    JSONObject jObj = new JSONObject(stringaRis);

我认为它是在告诉您 stringaRis 的值为 "A" ... 并且不能将其解析为 JSON 对象。根本不是 JSON。