How to test if JSON object is empty in Java

前端 未结 15 2288

The JSON object I\'m receiving looks like this:

[{\"foo1\":\"bar1\", \"foo2\":\"bar2\", \"problemkey\": \"problemvalue\"}]

What I\'m trying

相关标签:
15条回答
  • 2020-12-14 00:26
    obj.length() == 0
    

    is what I would do.

    0 讨论(0)
  • 2020-12-14 00:26

    if you want to check for the json empty case, we can directly use below code

    String jsonString = {};
    JSONObject jsonObject = new JSONObject(jsonString);
    if(jsonObject.isEmpty()){
     System.out.println("json is empty");
    } else{
     System.out.println("json is not empty");
    }
    

    this may help you.

    0 讨论(0)
  • 2020-12-14 00:27

    A JSON notation {} represents an empty object, meaning an object without members. This is not the same as null. Neither it is string as you are trying to compare it with string "{}". I don't know which json library are you using, but try to look for method something like:

    isEmptyObject() 
    
    0 讨论(0)
  • 2020-12-14 00:28

    If JSON returned with following structure when records is an ArrayNode:

    {}client 
      records[]
    

    and you want to check if records node has something in it then you can do it using a method size();

    if (recordNodes.get(i).size() != 0) {}
    
    0 讨论(0)
  • 2020-12-14 00:33

    I would do the following to check for an empty object

    obj.similar(new JSONObject())
    
    0 讨论(0)
  • 2020-12-14 00:36
    Object getResult = obj.get("dps"); 
    if (getResult != null && getResult instanceof java.util.Map && (java.util.Map)getResult.isEmpty()) {
        handleEmptyDps(); 
    } 
    else {
        handleResult(getResult); 
    }
    
    0 讨论(0)
提交回复
热议问题