【问题标题】:How to test if a JSONObject is null or doesn't exist如何测试 JSONObject 是否为空或不存在
【发布时间】:2012-09-25 14:47:33
【问题描述】:

我有一组JSONObject 值,我从服务器接收并对其进行操作。大多数时候我得到一个带有值的JSONObject(比如说统计数据),有时,它返回一个带有代码和错误描述的Error对象。

如何构造我的代码,以便它在返回错误时不会中断。我以为我可以做到这一点,但不起作用。

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"));
        }
    }
}

【问题讨论】:

  • 目前有什么问题?

标签: java android json


【解决方案1】:

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

保守的用法可能是;

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

【讨论】:

  • 很有趣,我单独使用了 isNull() 方法,但遇到了同样的麻烦。
  • 发布您收到的带有 ERROR 键的 JSON 消息并提供异常类型,我们将立即对其进行排序。 :)
  • 你有没有得到这个排序@sparrow?
  • @RobertN : "has" 检查 JSONObject 是否包含特定键。 “isNull”检查与键关联的值是否为空或没有值。 json.org/javadoc/org/json/…
  • @OceanLife 如果你使用 isNull(String s),你可以跳过 has(String s)。 isNull(String s) 检查与 has(String s) 相同,并额外检查 value 是否为 'null'
【解决方案2】:

可能有点晚了(这是肯定的),但将其发布给未来的读者

你可以使用JSONObject optJSONObject (String 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 functions 的整个家族要么返回 null,要么您也可以使用重载版本使它们返回任何预定义的值。 例如

String optString (String name, String fallback)

如果存在则返回按名称映射的值,如果存在则强制 必要的,或者如果不存在这样的映射则回退。

其中coercing的意思是,它会尝试将值转换为String类型


@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!");
    }
}

【讨论】:

    【解决方案3】:

    在 JSONObject 中有一个“Has”方法可以用来确定密钥。

    我不知道这是否可行,但它看起来可信。

    public void processResult(JSONObject result) {
    
        if(result.has("ERROR"))
        {
            JSONObject error = result.getJSONObject("ERROR")
            String error_detail = error.getString("DESCRIPTION");
    
            if(error_detail != null)
            {
                //Show Error Login
                finish();
            }
        }
        else if(result.has("STATISTICS"))
        {
            JSONObject info = result.getJSONObject("STATISTICS");
            String stats = info.getString("Production Stats");
    
            //Do something
        }
        else
        {
            throw new Exception("Could not parse JSON Object!");
        }
    }
    

    【讨论】:

      【解决方案4】:

      有时使用 NULL 对象比使用 Java 的 null 值更方便,也更清楚。

      • JSONObject.NULL.equals(null) 返回真。

        JSONObject.NULL.toString() 返回“null”。

      例子:

      System.out.println(test.get("address").equals(null)); // 首选方式 System.out.println(test.getString("address").equals("null"));

      source -- JSONObject oracle docs

      【讨论】:

        【解决方案5】:

        请注意:

        使用 EE8 json 规范,我可以进行异常安全的获取:

        result.asJsonObject().getString("ERROR", null);
        

        但是,如果我想进行检查,我可以这样做:

        result.asJsonObject().get("ERROR").equals(JsonValue.NULL)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-02-27
          • 2011-09-17
          • 2018-10-13
          • 1970-01-01
          • 2015-11-30
          • 1970-01-01
          • 2019-03-22
          • 2011-11-26
          相关资源
          最近更新 更多