解析JSON而不继承Try-Catch块 [英] Parse JSON without succession of Try-Catch blocks

查看:308
本文介绍了解析JSON而不继承Try-Catch块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解析JSON,但是每次获取值时,都必须将指令放入try-catch块中.这是一个示例:

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....

我不在乎指令是否出现异常.因此,我想知道是否可以删除所有try-catch块并将所有指令放在一起.

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.

实际上,这更多是一个Java问题,而不仅仅是一个Android问题....

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

编辑

只需澄清问题所在. 当由于没有我要查找的标记而导致出现异常时,我将继续进行下一个标记检查,而不是处理异常.为此,我必须编写上面发布的代码,因此要编写一系列try-catch块.我一直在寻找更快(更优雅)的解决方案.

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.

推荐答案

您可以使用opt方法而不是get方法,前提是不存在密钥是可以的.如果密钥不是可选的,并且您的应用程序无法从并非全部存在的那些字段中恢复,则绝对应使用get方法,如果遇到错误,则快速失败.

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.

您可以使用的另一种有用的方法是has()方法.这将检查给定密钥是否存在映射. (例如if (json.has("id") id = json.optString("id"))).

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"))).

这篇关于解析JSON而不继承Try-Catch块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆