How to test if JSON object is empty in Java

前端 未结 15 2287

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

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

What I\'m trying

相关标签:
15条回答
  • 2020-12-14 00:37

    If you're okay with a hack -

    obj.toString().equals("{}");
    

    Serializing the object is expensive and moreso for large objects, but it's good to understand that JSON is transparent as a string, and therefore looking at the string representation is something you can always do to solve a problem.

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

    I have added isEmpty() methods on JSONObject and JSONArray()

     //on JSONObject 
     public Boolean isEmpty(){         
         return !this.keys().hasNext();
     }
    

    ...

    //on JSONArray
    public Boolean isEmpty(){
        return this.length()==0;        
    }
    

    you can get it here https://github.com/kommradHomer/JSON-java

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

    If empty array:

    .size() == 0
    

    if empty object:

    .length() == 0
    
    0 讨论(0)
提交回复
热议问题