复杂 json 解析未发现异常 java

complex json parsing not found exception java

我有一个 json 解析器,它解析一个复杂的 json 对象。有些对象有键 'a2' 而有些则没有。当对象没有键 "a2" 时,我想 return "not found"。这是我的代码:

String JSON = {"IP":{"string":"1.2.3.4"},"rrr":{"test":{"a1":"36","a2":"www.abc.com"}}}

public String getParameters(JSONObject json) throws JSONException {

    String jsonString;
    if ((jsonString = json.getJSONObject("rrr").getJSONObject("test")
            .getString("a2")) != null) {
        return jsonString;
    } else
        return "not Found";

        }

但是代码中发生的事情是,如果解析器没有找到 'a2',它会抛出一个异常并且 returns。我要对代码进行哪些更改才能使其正常工作?

getTYPE(key) 方法的情况下,如果找不到 key 元素,它们将抛出异常。

为了避免这种情况,您可以使用 optTYPE(key),在这种情况下,它将 return null 或一些默认值。
optString 的情况下,它将 return 空字符串作为默认值,但您可以使用 optString(key, null) 指定您希望它成为 return null if key 元素将不存在。

所以你的代码看起来像

public String getParameters(JSONObject json) throws JSONException {

    String jsonString;
    if ((jsonString = json.getJSONObject("rrr").getJSONObject("test")
            .optString("a2",null)) != null) {
    //       ^^^            ^^^^ <- default value in case of lack of element
        return jsonString;
    } else
        return "not Found";

}