Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON without succession of Try-Catch blocks

Tags:

java

json

android

I would like to parse a JSON, but every time I get a value, I have to put the instruction in a try-catch block. Here is an example:

try {
        this.setID(jsonObject.getLong("id"));
    } catch (JSONException e) {
    }
    try {
        this.setName(jsonObject.getString("name"));
    } catch (JSONException e) {
    }
//and so on....

I don't care if an instruction arise an exception. So I was wondering if it is possible to delete all the try-catch blocks and put the instructions all together.

Actually it is more a java problem and not only an android problem....

EDIT

Just clarifying what is the problem. When an exception arises because there is not the tag I was looking for, I would continue with the next tag check instead of handling the exception. To do this, I have to write the code as I posted above, thus a succession of try-catch blocks. I was looking for a faster (and more elegant) solution.

like image 675
Daniele Vitali Avatar asked Oct 07 '13 17:10

Daniele Vitali


1 Answers

You can use the opt methods instead of the get methods, assuming that it's okay for the keys not to exist. If the keys are not optional, and your app cannot recover from those fields not all existing, you should definitely use the get methods and fail fast if you run into an error.

Another helpful method you can use is the has() method. This checks if there is a mapping for a given key. (e.g. if (json.has("id") id = json.optString("id"))).

like image 194
Kevin Coppock Avatar answered Sep 21 '22 17:09

Kevin Coppock