如何在 Java 中测试 JSON 对象是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19170338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:42:31  来源:igfitidea点击:

How to test if JSON object is empty in Java

javajson

提问by Classified

The JSON object I'm receiving looks like this:

我收到的 JSON 对象如下所示:

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

What I'm trying to test for is the existence of problemvalue. If problemvaluereturns a JSON Object, I'm happy. If it doesn't, it will return as {}. How do I test for this condition? I've tried several things to no avail.

我试图测试的是problemvalue. 如果problemvalue返回 JSON 对象,我很高兴。如果没有,它将作为{}. 我如何测试这种情况?我尝试了几件事都无济于事。

This is what I've tried thus far:

这是我迄今为止尝试过的:

//      if (obj.get("dps") == null) {  //didn't work
//      if (obj.get("dps").equals("{}")) {  //didn't work
if (obj.isNull("dps")) {  //didn't work
    System.out.println("No dps key");
}

I expected one of these lines to print "No dps key" because {"dps":{}}, but for whatever reason, it's not. I'm using org.json. The jar file is org.json-20120521.jar.

我希望其中一行打印“No dps key”,因为{"dps":{}},但无论出于何种原因,事实并非如此。我正在使用org.json. jar 文件是org.json-20120521.jar.

采纳答案by Scott Tesler

obj.length() == 0

is what I would do.

是我会做的。

回答by Orel Eraki

Try:

尝试:

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

回答by APerson

Try /*string with {}*/ string.trim().equalsIgnoreCase("{}")), maybe there is some extra spaces or something

试试看/*string with {}*/ string.trim().equalsIgnoreCase("{}")),也许有一些额外的空格或什么的

回答by Anderson

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:

JSON 表示法 {} 表示一个空对象,意思是一个没有成员的对象。这与空值不同。当您尝试将它与字符串“{}”进行比较时,它都不是字符串。我不知道您使用的是哪个 json 库,但请尝试查找类似以下内容的方法:

isEmptyObject() 

回答by Hot Licks

Object getResult = obj.get("dps"); 
if (getResult != null && getResult instanceof java.util.Map && (java.util.Map)getResult.isEmpty()) {
    handleEmptyDps(); 
} 
else {
    handleResult(getResult); 
}

回答by djechlin

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.

序列化对象是昂贵的,对于大对象更是如此,但最好理解 JSON 作为字符串是透明的,因此查看字符串表示是您始终可以解决问题的方法。

回答by user3487921

Use the following code:

使用以下代码:

if(json.isNull()!= null){  //returns true only if json is not null

}

回答by kommradHomer

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

我在 JSONObject 和 JSONArray() 上添加了 isEmpty() 方法

 //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

你可以在这里得到它https://github.com/kommradHomer/JSON-java

回答by sorjef

I would do the following to check for an empty object

我会执行以下操作来检查空对象

obj.similar(new JSONObject())

回答by Alex

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

如果记录为 ArrayNode 时 JSON 返回具有以下结构:

{}client 
  records[]

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

并且您想检查记录节点中是否有内容,那么您可以使用方法 size();

if (recordNodes.get(i).size() != 0) {}