Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
651 views
in Technique[技术] by (71.8m points)

java - unhandled exception org.json.jsonexception

I'm working on an android app, and the app must save a java object in json format into the SQLite database. I wrote the code for this operation, then they must extract the Json object and reconvert it into a Java Object. When I try to call the method for deserializing the json object in to a string, I found this error in Android Studio:unhandled exception org.json.jsonexception

When I try to catch JSONException e the program runs but don't deserialize the json object.

This is the code for the method:

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

Can you help me please?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, you need to catch the exception.

But when you catch it, you should not just throw it on the floor. Your application needs to do something about the exception. Or if you / it is not expecting an exception to occur at runtime, then at least you should report it. Here's a minimal example (for an Android app)

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

Of course, this does not solve your problem. The next thing you need to do is to figure out why you are getting the exception. Start by reading the exception message that you have logged to logcat.


Re this exception message:

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

I assume it is thrown by this line:

    JSONObject jObj = new JSONObject(stringaRis);

I think that it is telling you is that stringaRis has the value "A" ... and that cannot be parsed as a JSON object. It isn't JSON at all.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...