简体   繁体   English

如何测试 JSONObject 是否为空或不存在

[英]How to test if a JSONObject is null or doesn't exist

I have a set of JSONObject values which i receive from a server and operate on.我有一组JSONObject值,我从服务器接收并对其进行操作。 Most times I get a JSONObject with a value (let's say statistics) and sometimes, it returns an Error object with a code and a description of the error.大多数情况下,我得到一个带有值的JSONObject (比如说统计数据),有时,它返回一个带有代码和错误描述的Error对象。

How do I structure my code so that it doesn't break if it returns the error.我如何构造我的代码,以便它在返回错误时不会中断。 I thought I could do this, but doesn't work.我以为我可以做到这一点,但没有用。

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

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

A conservative usage could be;保守的用法可能是;

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

It might be little late(it is for sure) but posting it for future readers可能有点晚(这是肯定的),但将其发布给未来的读者

You can use JSONObject optJSONObject (String name) which will not throw any exception and您可以使用不会抛出任何异常的JSONObject optJSONObject (String name)

Returns the value mapped by name if it exists and is a JSONObject, or null otherwise.如果存在并且是 JSONObject,则返回按名称映射的值,否则返回 null。

so you can do所以你可以做

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

or if you just want to test nullity without fetching the value then或者如果您只想测试无效性而不获取值,那么

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

There is whole family of opt functions which either return null or you can also use the overloaded version to make them return any pre-defined values.有整个系列的opt 函数,它们要么返回null ,要么您也可以使用重载版本使它们返回任何预定义的值。 eg例如

String optString (String name, String fallback)

Returns the value mapped by name if it exists, coercing it if necessary, or fallback if no such mapping exists.如果存在,则返回按名称映射的值,必要时强制它,如果不存在此类映射,则回退。

where coercing mean, it will try to convert the value into String type其中coercing意味着,它将尝试将值转换为字符串类型


A modified version of the @TheMonkeyMan answer to eliminate redundant look-ups @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!");
    }
}

In JSONObject there is a 'Has' method that you can do to Determaine the key.在 JSONObject 中,您可以使用“Has”方法来确定密钥。

I have no idea if this will work but it looks Credible.我不知道这是否可行,但它看起来可信。

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

It is sometimes more convenient and less ambiguous to have a NULL object than to use Java's null value.有时,使用 NULL 对象比使用 Java 的 null 值更方便,也更不模糊。

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

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

Example:例子:

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

source -- JSONObject oracle docs来源——JSONObject oracle 文档

Just a note:只是一个说明:

With EE8 json specs, I can do an exception-safe get:使用 EE8 json 规范,我可以进行异常安全的获取:

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

if, however, I want to do a check I can do it with:但是,如果我想做一个检查,我可以这样做:

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

If at any point in your code, org.json.JSONObject json_object becomes null and you wish to avoid NullPointerException (java.lang.NullPointerException), then do check it as below:如果在您的代码中的任何一点, org.json.JSONObject json_object变为null并且您希望避免NullPointerException (java.lang.NullPointerException),请按如下方式进行检查:

if(json_object == null) {
   System.out.println("json_object is found as null");
  }
  else {
       System.out.println("json_object is found as not null");
  }

If in any case, your jsonobject is null.如果在任何情况下,您的 jsonobject 为空。 Then use this statement for checking jsonobject is null or not.然后使用此语句检查 jsonobject 是否为空。

if (!obj.get("data").isJsonNull()){
   //Not Null
}else{
   //Null
}

And for checking jsonobject is exist or not, use .has:要检查 jsonobject 是否存在,请使用 .has:

if (!obj.has("data")){
   //Not Exist
}else{
   //Exist
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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