简体   繁体   中英

Parse JSON without succession of Try-Catch blocks

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.

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. (eg if (json.has("id") id = json.optString("id")) ).

Maybe I didn't understand what you're asking, but why don't you put all calls to jsonObject within the same try-catch block?

try {
    this.setID(jsonObject.getLong("id"));
    this.setName(jsonObject.getString("name"));
} catch (JSONException e) {
    // log or consume it some other way
}

You should never just swallow exceptions. At least log an error.

Like @Sotirios was saying you can't disregard a json exception.

You can put all your json reading in a method and make that method throw the JSONException, like this:

    public void readJson(String json) throws JSONException{
     this.setID(jsonObject.getLong("id"));
     this.setName(jsonObject.getString("name"));
   }

but you steel have to do a try catch when you call that method:

    try {
            readJson(jLine);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

I think it is more of a library problem than anything else. A couple of JSON libraries in Java tend to add exceptions in their library calls as if the designer wanted to use invasive C-like error status codes but with the added weight of Java exceptions syntax. I can partially understand the motives for such an interface, but it looks really inelegant.

I would suggest using json-simple , which is too simple sometimes but gets the job done and stays out of the way.

Replace

jsonObject.getFoo("key")

with

jsonObject.optFoo("key")

If the key is not found, a null or similar default value is returned instead of an exception being thrown.

If you want cleaner syntax, you should look at gson . If you know what the json will look like, nothing beats it.

If your JSON looks like this:

{
    "id": 432942039,
    "name": "My name",
    "values": [0, 1, 2, 3]
}

You'd create a POJO class that looks like this:

public class MyClass {
    public MyClass() {}
    private long id;
    private String name;
    private int[] values;
}

And parse it like this:

private parse(String jsonString) {
    Gson gson = new Gson();
    MyClass myObject = gson.fromJson(jsonString, MyClass.class);
}

And that's it. No setters are needed; it uses reflection to match the fields. No annotations. No errors if there are fields in your JSON string that don't match anything in your POJO and vice versa.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM