如何测试 JSON 对象是否为空或不存在

2022-08-31 22:15:29

我有一组从服务器接收并操作的值。大多数时候,我得到一个值(假设是统计),有时,它会返回一个带有代码和错误描述的对象。JSONObjectJSONObjectError

如何构建代码,以便在返回错误时不会中断。我以为我可以这样做,但行不通。

public void processResult(JSONObject result) {
    try {
        if(result.getJSONObject(ERROR) != null ){
            JSONObject error = result.getJSONObject(ERROR);
            String error_detail = error.getString(DESCRIPTION);
            if(!error_detail.equals(null)) {
                //show error login here
            }
            finish();
        }
        else {
            JSONObject info = result.getJSONObject(STATISTICS);
            String stats = info.getString("production Stats"));
        }
    }
}

答案 1

使用和.has(String).isNull(String)

保守的用法可能是;

    if (record.has("my_object_name") && !record.isNull("my_object_name")) {
        // Do something with object.
      }

答案 2

它可能有点晚(这是肯定的),但发布它供未来的读者使用

您可以使用JSONObject optJSONObject(字符串名称),它不会引发任何异常,并且

返回按 name 映射的值(如果该值存在并且是 JSONObject),否则返回 null。

所以你可以做

JSONObject obj = null;
if( (obj = result.optJSONObject("ERROR"))!=null ){
      // it's an error , now you can fetch the error object values from obj
}

或者,如果您只想在不获取值的情况下测试空性,则

if( result.optJSONObject("ERROR")!=null ){
    // error object found 
}

有整个系列的opt函数可以返回,也可以使用重载版本使它们返回任何预定义的值。例如null

String optString (String name, String fallback)

返回按 name 映射的值(如果存在),如有必要强制执行该值,如果不存在此类映射,则返回回退。

其中 mean,它将尝试将值转换为字符串类型coercing


@TheMonkeyMan答案的修改版本,以消除冗余查找

public void processResult(JSONObject result) {
    JSONObject obj = null;
    if( (obj = result.optJSONObject("ERROR"))!=null ){
       //^^^^ either assign null or jsonobject to obj
      //  if not null then  found error object  , execute if body                              
        String error_detail = obj.optString("DESCRIPTION","Something went wrong");
        //either show error message from server or default string as "Something went wrong"
        finish(); // kill the current activity 
    }
    else if( (obj = result.optJSONObject("STATISTICS"))!=null ){
        String stats = obj.optString("Production Stats");
        //Do something
    }
    else
    {
        throw new Exception("Could not parse JSON Object!");
    }
}